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

如何在JavaScript中合并两个对象数组并累加同名对象的age值

合并JavaScript数组并累加重复项的age值

你可以通过数组合并 + reduce累加 + 对象转数组的方式实现需求,核心是利用name作为唯一标识判断重复项并累加age,具体实现如下:

完整代码示例

let array1 = [{name:'jane', age: 20}, {name:'john', age: 30}];
let array2 = [{name:'bob', age: 50}, {name:'john', age: 25}];

// 合并两个数组(不修改原数组)
const combinedArray = [...array1, ...array2];

// 使用reduce构建累加对象,再转换为数组
const result = Object.values(
  combinedArray.reduce((accumulator, currentItem) => {
    // 如果当前name已存在,累加age
    if (accumulator[currentItem.name]) {
      accumulator[currentItem.name].age += currentItem.age;
    } else {
      // 不存在则存入新对象(浅拷贝避免影响原数组)
      accumulator[currentItem.name] = {...currentItem};
    }
    return accumulator;
  }, {}) // 初始值为空对象
);

console.log(result);
// 输出结果:[{name:'jane', age:20}, {name:'bob', age:50}, {name:'john', age:55}]

代码说明

  • 合并数组:用扩展运算符[...array1, ...array2]创建新数组,避免修改原始输入数组
  • reduce累加:遍历合并后的数组,以name为键存储对象,重复项自动累加age
  • 对象转数组:通过Object.values()将累加对象的取值转换为最终的数组格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:40:21