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

如何从对象数组中对相同键对应的值进行求和计算

对对象数组中相同键对应的值求和

要实现将数组中相同键对应的值累加,最简洁高效的方式是使用JavaScript的reduce方法,它专门用于处理这类累加聚合的场景。

方法一:使用reduce + for...in遍历键

const inputArr = [{a:2}, {b:3}, {a:2}, {b:3}];
const sumResult = inputArr.reduce((accumulator, currentObj) => {
  // 遍历当前对象的所有键
  for (const key in currentObj) {
    // 若累加器中已有该键则累加值,否则初始化为当前值
    accumulator[key] = (accumulator[key] || 0) + currentObj[key];
  }
  return accumulator;
}, {}); // 初始值设为空对象,作为累加的起点

console.log(sumResult); // 输出: {a:4, b:6}

方法二:使用reduce + Object.entries遍历键值对

如果更倾向于明确的键值对遍历,可以用Object.entries来获取当前对象的键值数组:

const inputArr = [{a:2}, {b:3}, {a:2}, {b:3}];
const sumResult = inputArr.reduce((accumulator, currentObj) => {
  Object.entries(currentObj).forEach(([key, value]) => {
    // 用空值合并运算符`??`替代`||`,避免0等 falsy 值被误判
    accumulator[key] = (accumulator[key] ?? 0) + value;
  });
  return accumulator;
}, {});

console.log(sumResult); // 输出: {a:4, b:6}

说明

这两种方法都能处理数组中对象包含多个键的情况(比如某对象是{a:1, b:2}),会自动遍历所有键并完成累加。reduce方法会逐个处理数组元素,最终返回聚合后的结果对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:15:36