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

如何合并两个对象数组:保留旧值、扩展新值并按需扩容?

合并对象数组并合并对应notes项的实现方法

首先得说,没有原生JavaScript方法能直接实现你这个定制化的合并需求,因为你的需求逻辑比较特定:要匹配相同title的对象,然后对应索引的notes项里的body要拼接,还要保留其中一个数组里多出来的notes项。不过自己写个merge函数也不难,我给你整理了完整的实现方案:

先修正你给出的输入格式(让它符合JS语法规范):

const array1 = [
  { 
    title: "title", 
    notes: [
      { body: "text" },
      { body: "text" },
      { body: "some other text" }
    ] 
  }
];

const array2 = [
  { 
    title: "title", 
    notes: [
      { body: "text" },
      { body: "text sfhhda" }
    ] 
  }
];

然后是实现merge函数的代码:

function merge(arr1, arr2) {
  // 用title作为键创建映射,方便快速匹配相同标题的对象
  const mergedMap = new Map();

  // 先把第一个数组的对象存入映射,做浅拷贝避免修改原数组
  arr1.forEach(item => {
    mergedMap.set(item.title, { ...item, notes: [...item.notes] });
  });

  // 遍历第二个数组,处理合并逻辑
  arr2.forEach(item => {
    if (mergedMap.has(item.title)) {
      const existingItem = mergedMap.get(item.title);
      // 合并notes数组:对应索引的body拼接,多余项保留
      const mergedNotes = existingItem.notes.map((note, index) => {
        const otherNote = item.notes[index];
        if (otherNote) {
          return { body: `${note.body} ${otherNote.body}`.trim() };
        }
        return { ...note };
      });
      // 如果第二个数组的notes更长,把多出来的项追加进去
      if (item.notes.length > existingItem.notes.length) {
        mergedNotes.push(...item.notes.slice(existingItem.notes.length));
      }
      existingItem.notes = mergedNotes;
    } else {
      // 第一个数组没有对应title的话,直接加入映射
      mergedMap.set(item.title, { ...item });
    }
  });

  // 把映射转成数组返回
  return Array.from(mergedMap.values());
}

// 测试调用
console.log(merge(array1, array2));

这个函数的核心逻辑:

  • 用Map来快速匹配相同title的对象,避免重复遍历数组
  • 处理notes时,优先拼接对应索引的body内容,同时保留任意一方多出来的notes项
  • 全程用浅拷贝操作,不会修改原始输入数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:15:02