如何按年份和学期多条件对对象数组的worthAmountEGP求和?
问题:按年份和学期分组求和
worthAmountEGP字段 原始数据
[ { "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 } ]
需求
根据年份+学期的唯一组合,对数组中worthAmountEGP字段的值进行求和,最终保留每个组合的年份、学期及求和结果。
尝试的代码
const transformed = Object.values( aa.reduce((acc, { term, worthAmountEGP, year }) => { acc[term] = acc[term] || { term, worthAmountEGP: 0 }; acc[term].worthAmountEGP += worthAmountEGP; return acc; }, {}) );
当前输出
Transformed: [ { term: 1, worthAmountEGP: 5000000 }, { term: 2, worthAmountEGP: 3200000 }, ]
期望输出
[ { 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}, ]
解决方案
原代码仅用term作为分组key,导致不同年份的同term数据被合并。需要将年份+学期的组合作为唯一key,才能实现按两个条件分组求和。
修正后的代码:
const transformed = Object.values( aa.reduce((acc, { term, worthAmountEGP, year }) => { // 生成年份+学期的唯一标识key const key = `${year}-${term}`; // 若该key不存在,初始化对应的对象 if (!acc[key]) { acc[key] = { year, term, worthAmountEGP: 0 }; } // 累加对应字段的值 acc[key].worthAmountEGP += worthAmountEGP; return acc; }, {}) );
执行后即可得到符合期望的输出,其中2021年term2的worthAmountEGP会正确计算为1000000 + 400000 = 1400000,其余分组的求和结果也与预期一致。
内容的提问来源于stack exchange,提问作者Mohamed Khalifa
相关产品推荐
相关产品推荐

