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

JavaScript如何将第二数组对象值合并到第一对象数组且不产生重复项

实现方案

你可以通过两层Array.prototype.map按索引对应合并实现,不会生成重复数据,代码如下:

const firstArray = [
    {
      first: "01",
      data: [{ id: "012345" }, { id: "0123456" }, { id: "0123457" }]
    },
    {
      first: "02",
      data: [{ id: "9998989" }, { id: "1223" }, { id: "345666" }]
    },
    {
      first: "03",
      data: [{ id: "567888" }, { id: "2345" }, { id: "09876" }]
    }
  ];
const secondArray = [{ data: "abc" }, { data: "efg" }, { data: "hij" }];

// 实现逻辑(不修改原数组,无副作用)
const mergedResult = firstArray.map(parentItem => {
  return {
    // 拷贝原父级对象其他属性
    ...parentItem,
    // 遍历子级data数组,按索引匹配secondArray的元素合并
    data: parentItem.data.map((childItem, index) => {
      return {
        ...childItem,
        ...secondArray[index]
      }
    })
  }
})

console.log(mergedResult) // 输出完全符合预期结果

原理说明

  • 第一层遍历firstArray的每个父元素,保留原有first字段
  • 第二层遍历每个父元素的data子数组,通过当前遍历的下标index,对应取secondArray同下标的元素合并到子对象中
  • 全程使用展开运算符做浅拷贝,不会修改原数组的原有数据,也不会因为循环逻辑错误生成重复项,你之前用for循环出现重复大概率是嵌套逻辑错误,没有按索引对应赋值反而重复追加了元素

兼容写法(ES5及以下)

如果需要兼容不支持ES6展开运算符的环境,可以用Object.assign实现:

var mergedResult = firstArray.map(function(parentItem) {
  var newParent = Object.assign({}, parentItem);
  newParent.data = parentItem.data.map(function(childItem, index) {
    return Object.assign({}, childItem, secondArray[index]);
  });
  return newParent;
});

注意事项

该方案默认firstArray每个元素的data数组长度和secondArray长度一致,若实际场景中长度不一致,可自行添加下标越界的判断逻辑,给超出部分设置默认值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:24:01