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

如何用密钥数组过滤对象数组,统一新增日期的时间范围?

问题解决方案

核心问题很明确:你的过滤逻辑是在Tuesdays对象被加入daysArray之前执行的,这时候数组里根本找不到它,自然过滤不会生效。

给你两种直接可行的修改方式:

方式一:先过滤再添加

先把Tuesdays的时间范围处理好,再将它加入数组,这是最直接的逻辑:

// 先定义原始的Tuesdays对象
const tuesdaysObj = {
  day: 'Tuesdays',
  timeRanges: [/* 你的6个原始时间范围 */]
};

// 用removedKeys过滤掉不需要的时间范围
tuesdaysObj.timeRanges = tuesdaysObj.timeRanges.filter(range => {
  // 这里根据你的实际key规则写判断,比如排除包含removedKeys里的start/end key的项
  return !removedKeys.includes(range['start time KEY']) && !removedKeys.includes(range['end time KEY']);
});

// 最后把处理好的对象加入数组
daysArray.push(tuesdaysObj);

方式二:先添加再立即过滤

如果业务逻辑要求必须先把原始对象加入数组,那添加后立刻找到它执行过滤:

// 先把原始Tuesdays对象加入数组
daysArray.push(tuesdaysObj);

// 从数组中找到Tuesdays对象
const targetDay = daysArray.find(item => item.day === 'Tuesdays');
if (targetDay) {
  // 执行过滤
  targetDay.timeRanges = targetDay.timeRanges.filter(range => {
    return !removedKeys.includes(range['start time KEY']) && !removedKeys.includes(range['end time KEY']);
  });
} else {
  console.log('Tuesdays not found in daysArray.'); // 现在这个日志基本不会触发
}

关键逻辑就是:过滤操作必须在能拿到Tuesdays对象的引用之后执行——要么直接操作未加入数组的对象,要么加入后立刻从数组中找到它再处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 16:32:35