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

如何对对象数组中各键对应的值进行求和计算?

按键对对象数组的值求和

现有对象数组:

[{A: 47.5, B: 23.4, C: 32.4, D: 12.5, E: 18.2},{D: 10, C: 22.5, A: 85.7, E: 48.6},{B: 93.45, D: 37.1, E: 66.34},{A: 0, D: 0,  C: 0,  B: 8.50, E: 78.5},{C: 0, A: 0, B: 11.7, E: 0},{E: 89.4, D: 16.5, B: 29.7, A: 84.5}]

我原本尝试了一段只适用于有序数组的代码,但无法实现按键求和:

const totals = new Array(StoreResumeRows.length).fill(0)
StoreResumeRows.map((matrixRow: any) => {
  for(let index = 0; index < totals.length; index++){
    totals[index] += matrixRow[index]
  }
})
console.log(totals)

需要得到各键对应值的总和,期望输出:

[{A: 217.7, B: 166.75, C: 54.9, D: 76.1, E: 301.04}]

解决方案

原代码的问题在于通过数字索引访问对象属性,但对象属性是无序的,无法用索引直接获取。正确思路是遍历每个对象的键,针对性累加对应值,推荐使用reduce方法实现:

const StoreResumeRows = [{A: 47.5, B: 23.4, C: 32.4, D: 12.5, E: 18.2},{D: 10, C: 22.5, A: 85.7, E: 48.6},{B: 93.45, D: 37.1, E: 66.34},{A: 0, D: 0,  C: 0,  B: 8.50, E: 78.5},{C: 0, A: 0, B: 11.7, E: 0},{E: 89.4, D: 16.5, B: 29.7, A: 84.5}];

const totalObj = StoreResumeRows.reduce((acc, curr) => {
  // 遍历当前对象的所有键
  for (const key in curr) {
    // 累加对应键的值,无初始值则设为0后再累加
    acc[key] = (acc[key] || 0) + curr[key];
  }
  return acc;
}, {});

// 包装成数组形式,匹配期望输出格式
const totals = [totalObj];
console.log(totals);

代码说明

  • reduce初始化空对象作为累加器,逐个处理数组中的每个对象
  • 遍历当前对象的键,判断累加器中是否存在该键:不存在则初始化为0,再加上当前值;存在则直接累加
  • 最后将结果对象包装为数组,得到符合要求的输出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:55:54