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

如何遍历对象数组,按name属性分组并统计amount总和?

按姓名分组汇总金额的实现方案

给定包含姓名与金额的对象数组,需要按name属性分组并汇总每组的amount值,最终输出姓名 - 总金额(总金额)格式的结果,以下是两种实用实现方式:

方法一:使用Array.reduce()构建汇总对象

这是最常用的分组求和方式,通过累加器对象存储每组的总金额:

const arr = [
  { name: "person 1", amount: 154 },
  { name: "person 2", amount: 240 },
  { name: "person 1", amount: 100 },
  { name: "person 2", amount: 160 },
  { name: "person 2", amount: 140 },
  { name: "person 1", amount: 180 },
];

// 分组求和
const sumByPerson = arr.reduce((acc, current) => {
  acc[current.name] = (acc[current.name] || 0) + current.amount;
  return acc;
}, {});

// 转换为目标格式
const result = Object.entries(sumByPerson).map(([name, total]) => `${name} - ${total}(总金额)`);

// 输出结果
console.log(result);
// 输出:["person 1 - 434(总金额)", "person 2 - 540(总金额)"]

如果需要直接输出换行的字符串形式,可使用join方法:

console.log(result.join('\n'));
// 输出:
// person 1 - 434(总金额)
// person 2 - 540(总金额)

方法二:使用Map保持插入顺序

如果需要保留姓名在原数组中首次出现的顺序,推荐使用Map实现:

const arr = [
  { name: "person 1", amount: 154 },
  { name: "person 2", amount: 240 },
  { name: "person 1", amount: 100 },
  { name: "person 2", amount: 160 },
  { name: "person 2", amount: 140 },
  { name: "person 1", amount: 180 },
];

const sumMap = new Map();

arr.forEach(item => {
  const currentTotal = sumMap.get(item.name) || 0;
  sumMap.set(item.name, currentTotal + item.amount);
});

// 转换为目标格式数组
const result = Array.from(sumMap, ([name, total]) => `${name} - ${total}(总金额)`);

console.log(result);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:15:44