两个数组的对象如何合并相同项

如果你想在合并两个数组对象的同时,将两个数组中相同 id 的对象合并成一个,则可以按照以下步骤进行实现:

  1. 使用 Array.prototype.concat() 方法将两个数组连接在一起;
  2. 使用 Array.prototype.reduce() 方法将所有对象合并成一个,对相同 id 的对象进行合并;
  3. 返回合并后的对象数组。

下面是一个示例代码:

const array1 = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }];
const array2 = [{ id: 2, age: 20 }, { id: 3, age: 21 }, { id: 4, age: 22 }];

const mergedArray = array1.concat(array2)
  .reduce((accumulator, currentObj) => {
    const existingObj = accumulator.find(obj => obj.id === currentObj.id);
    if (existingObj) {
      Object.assign(existingObj, currentObj);
    } else {
      accumulator.push(currentObj);
    }
    return accumulator;
  }, []);

console.log(mergedArray);

在上面的代码中,我们首先使用 concat() 方法将 array1 和 array2 连接在一起,形成一个新的数组 mergedArray。然后,我们使用 reduce() 方法对 mergedArray 进行遍历,并判断当前对象的 id 是否已经在累加器中存在。

如果存在,则获取已经存在的对象并使用 Object.assign() 方法将当前对象合并到已经存在的对象中;如果不存在,则将当前对象添加到累加器中。

最后,我们得到了一个合并了两个数组对象并合并相同项的新数组 mergedArray

输出结果:

[
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob', age: 20 },
  { id: 3, name: 'Charlie', age: 21 },
  { id: 4, age: 22 }
]

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值