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

如何在Node.js中查找JavaScript对象数组中匹配时间的Id?

针对你的需求,这里提供几种简单高效的Node.js实现方案,因为数组规模很小(最多100个元素),无需复杂优化:

方法1:filter + map 组合遍历

先筛选出符合条件的对象,再提取对应的Id:

const dynamicObjectArray = [
  {Id: 1422859025, FromTime: "2023-02-12T19:00:00Z", ToTime: "2023-02-12T20:00:00Z"},
  {Id: 1422859027, FromTime: "2023-02-12T18:00:00Z", ToTime: "2023-02-12T19:00:00Z"}
];

const targetTime = "2023-02-12T19:00:00Z";

const matchedIds = dynamicObjectArray
  .filter(obj => obj.FromTime === targetTime || obj.ToTime === targetTime)
  .map(obj => obj.Id);

console.log(matchedIds); // 输出:[1422859025, 1422859027]

方法2:reduce 一次遍历完成

通过一次遍历同时完成筛选和Id收集,代码更紧凑:

const dynamicObjectArray = [
  {Id: 1422859025, FromTime: "2023-02-12T19:00:00Z", ToTime: "2023-02-12T20:00:00Z"},
  {Id: 1422859027, FromTime: "2023-02-12T18:00:00Z", ToTime: "2023-02-12T19:00:00Z"}
];

const targetTime = "2023-02-12T19:00:00Z";

const matchedIds = dynamicObjectArray.reduce((acc, obj) => {
  if (obj.FromTime === targetTime || obj.ToTime === targetTime) {
    acc.push(obj.Id);
  }
  return acc;
}, []);

console.log(matchedIds); // 输出:[1422859025, 1422859027]

两种方法在小规模数组下性能差异可忽略,可根据个人代码习惯选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:50:19