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

如何按指定date键合并对象数组,保留属性值为数组不覆盖

按date键合并对象数组,属性值转为数组不覆盖

嘿,这个场景我之前做日程类功能的时候刚好碰到过,给你分享个实用的实现方法~

核心思路是用Array.reduce()来做分组聚合,把相同date的对象合并,同时把对应属性的值收集成数组,完全不会覆盖初始属性。

固定属性的实现(适合已知属性的场景)

如果你的对象属性固定(比如只有date、finishTime、startTime),可以写得更直白:

const input = [
  { "date": "2020-07-14", "finishTime": "22:00", "startTime": "13:30" },
  { "date": "2020-07-14", "finishTime": "12:00", "startTime": "08:00" }
];

const mergedResult = Object.values(input.reduce((acc, currentItem) => {
  // 用date作为分组的唯一标识
  const dateKey = currentItem.date;
  
  if (!acc[dateKey]) {
    // 第一次遇到这个date,初始化合并对象
    acc[dateKey] = {
      date: dateKey,
      finishTime: [currentItem.finishTime],
      startTime: [currentItem.startTime]
    };
  } else {
    // 已有该date的分组,把当前属性值追加到对应数组
    acc[dateKey].finishTime.push(currentItem.finishTime);
    acc[dateKey].startTime.push(currentItem.startTime);
  }
  
  return acc;
}, {}));

console.log(mergedResult);
// 输出:[{ "date": "2020-07-14", "finishTime": ["22:00", "12:00"], "startTime": ["13:30", "08:00"] }]

动态属性的实现(适合属性不固定的场景)

如果以后可能新增其他属性,不想每次都修改代码,可以用动态遍历属性的方式,扩展性更强:

const input = [
  { "date": "2020-07-14", "finishTime": "22:00", "startTime": "13:30" },
  { "date": "2020-07-14", "finishTime": "12:00", "startTime": "08:00", "remark": "上午场" }
];

const mergedResult = Object.values(input.reduce((acc, currentItem) => {
  const dateKey = currentItem.date;
  
  if (!acc[dateKey]) {
    // 动态初始化所有属性:date保持原值,其他属性转为数组
    acc[dateKey] = Object.fromEntries(
      Object.entries(currentItem).map(([key, value]) => 
        [key, key === 'date' ? value : [value]]
      )
    );
  } else {
    // 动态遍历所有非date属性,追加值到对应数组
    Object.entries(currentItem).forEach(([key, value]) => {
      if (key !== 'date') {
        acc[dateKey][key].push(value);
      }
    });
  }
  
  return acc;
}, {}));

console.log(mergedResult);
// 输出:[{ "date": "2020-07-14", "finishTime": ["22:00", "12:00"], "startTime": ["13:30", "08:00"], "remark": ["上午场"] }]

逻辑说明

  1. reduce()的累加器acc用来临时存储按date分组的对象,键是date值,值是合并后的对象。
  2. 遍历每个对象时,判断当前date是否已在累加器中:
    • 不存在则创建新对象,将非date的属性初始化为包含当前值的数组。
    • 存在则将当前对象的属性值追加到对应数组中。
  3. 最后用Object.values()把累加器中的分组对象转为数组,得到最终结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 13:47:54