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

如何过滤对象数组,保留event_dates日期非null的事件?

过滤事件数组中日期为null的元素

我有一个包含事件的对象数组,示例如下:

[
  {
    "id": "abc123",
    "name": {
      "fi": "The name of the event in finnish",
      "en": "The name of the event in english",
      "sv": "samma på svenska",
      "zh": "标题"
    },
    "description": {
      "intro": "",
      "body": ""
    },
    "event_dates": {
      "starting_day": "2025-10-24T16:00:00.000Z",
      "ending_day": "2025-10-24T17:00:00.000Z"
    }
  },
  {
    "id": "123efg",
    "name": {
      "fi": "The name of the event in finnish",
      "en": "The name of the event in english",
      "sv": "samma på svenska",
      "zh": "标题"
    },
    "description": {
      "intro": "",
      "body": ""
    },
    "event_dates": {
      "starting_day": null,
      "ending_day": null
    }
  }
]

数组中部分事件的starting_day和ending_day值为null,需要编写函数过滤掉这些日期值为null的事件,输出仅包含日期非null事件的数组。


最简洁的实现方式是使用数组的filter方法,直接判断事件的两个日期字段是否都不为null:

const filteredEvents = events.filter(event => 
  event.event_dates.starting_day !== null && event.event_dates.ending_day !== null
);

说明

  • filter方法会遍历原数组,仅保留回调函数返回true的元素
  • 上述逻辑为:只有当starting_day和ending_day都不为null时,才保留该事件
  • 若需求为「只要其中一个日期不为null就保留」,只需将&&替换为||即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:17:28