
本文介绍如何使用 JavaScript 的 reduce 配合 Map,按 year 和 term 组合键对对象数组中 worthAmountEGP 字段进行分组求和,精准生成符合多维条件的聚合结果。
本文介绍如何使用 javascript 的 `reduce` 配合 `map`,按 `year` 和 `term` 组合键对对象数组中 `worthamountegp` 字段进行分组求和,精准生成符合多维条件的聚合结果。
在实际业务开发中(如教务系统、财务统计或教育经费汇总),我们常需对嵌套结构的数组按多个字段(如年份 + 学期)进行分组聚合。原始代码仅以 term 为键,导致跨年数据被错误合并;而正确方案必须将 year 与 term 共同构成唯一分组标识。
核心思路是:构造复合键 → 利用 Map 避免对象键名冲突 → 深拷贝初始项 → 增量累加数值字段。Map 相比普通对象更可靠:它支持任意类型键(此处用字符串键),且无原型链干扰,has() / get() / set() 接口语义清晰。
以下是完整可运行的实现:
const data = [
{ "year": 2020, "term": 1, "worthAmountEGP": 0 },
{ "year": 2020, "term": 2, "worthAmountEGP": 300000 },
{ "year": 2021, "term": 1, "worthAmountEGP": 0 },
{ "year": 2021, "term": 2, "worthAmountEGP": 1000000 },
{ "year": 2021, "term": 1, "worthAmountEGP": 0 },
{ "year": 2021, "term": 2, "worthAmountEGP": 400000 },
{ "year": 2022, "term": 1, "worthAmountEGP": 0 },
{ "year": 2022, "term": 2, "worthAmountEGP": 1000000 }
];
const result = Array.from(
data.reduce((acc, obj) => {
const key = `${obj.year}---${obj.term}`; // 复合键确保 year+term 唯一性
if (!acc.has(key)) {
acc.set(key, { ...obj }); // 浅拷贝保留 year/term,初始化 worthAmountEGP
} else {
acc.get(key).worthAmountEGP += obj.worthAmountEGP; // 累加金额
}
return acc;
}, new Map())
).map(([_, value]) => value); // 提取 Map.values() 并转为数组
console.log(result);
// 输出:
// [
// { term: 1, worthAmountEGP: 0, year: 2020 },
// { term: 2, worthAmountEGP: 300000, year: 2020 },
// { term: 1, worthAmountEGP: 0, year: 2021 },
// { term: 2, worthAmountEGP: 1400000, year: 2021 },
// { term: 1, worthAmountEGP: 0, year: 2022 },
// { term: 2, worthAmountEGP: 1000000, year: 2022 }
// ]
✅ 关键要点说明:
- 键设计:使用 year---term 格式(而非 year-term)可避免 2021-12 与 202-12 等潜在解析歧义;若字段值含特殊字符,建议改用 JSON.stringify([obj.year, obj.term]) 更健壮。
- 拷贝策略:{ ...obj } 是浅拷贝,适用于本例中无嵌套对象的结构;若存在深层属性,需改用结构化克隆(如 structuredClone(obj))或第三方库。
- 性能优势:Map 的 O(1) 查找效率优于多次 find() 或嵌套循环,尤其在大数据量下表现更优。
- 扩展性提示:如需同时聚合多个数值字段(如 taxAmount, discount),可在 if (!acc.has(key)) 分支中统一初始化所有目标字段为 0,再分别累加。
该方案逻辑清晰、零依赖、兼容现代浏览器及 Node.js 环境,是处理多维分组求和问题的标准实践。










