You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理sort_by操作中openingDates可能为null的情况?

解决openingDates为null时排序报错的问题

问题描述

我有如下结构的对象数组:

{
    "openingDates": [
        {
            "location": "Main St.",
            "openingDate": "2023-01-09T00:00:00Z"
        },
        {
            "location": "Northwood Park",
            "openingDate": "2006-01-10T00:00:00Z"
        }
    ]
}

我使用表达式 sort_by(openingDates, &openingDate)[0].openingDate 按openingDate排序并获取首个元素的openingDate值。但openingDates可能为null,此时执行排序会报错,请问如何在值为null时跳过排序操作?

解决方案

通过条件判断先校验openingDates的有效性,再决定是否执行排序操作,就能避免报错。

基础版(仅处理null情况)

用三元运算符先判断openingDates是否不为null,满足条件再执行排序取日期,否则返回null(可根据需求替换为其他默认值):

openingDates != null ? sort_by(openingDates, &openingDate)[0].openingDate : null

严谨版(同时处理null和空数组)

如果还要考虑openingDates为空数组的情况(避免[0]取元素时报错),可以增加数组长度的判断:

openingDates != null && length(openingDates) > 0 ? sort_by(openingDates, &openingDate)[0].openingDate : null

这个逻辑会先检查openingDates既不是null,又包含至少一个元素,只有满足这两个条件时才执行排序并提取首个日期;否则直接返回null,跳过排序操作。

内容的提问来源于stack exchange,提问作者spaceghost

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 19:15:38