如何使用js reduce对对象的某些属性求和?

时间:2019-12-08 10:35:01

标签: javascript arrays

嗨,我有以下数组:

let initial = [
[{name:"first",amount:1},{name:"second",amount:4},name:"third",amount:7}],
[{name:"first",amount:2},{name:"second",amount:5},name:"third",amount:8}],
[{name:"first",amount:3},{name:"second",amount:6},name:"third",amount:9}]
]

我的目标是垂直汇总每个对象的数量属性以获得最终数组:

let final = 
[{name:"first",amount:6(1+2+3)},{name:"second",amount:15(4+5+6)},name:"third",amount:24(7+8+9)}]

我想在这里使用reduce和map(如果需要)。也想得到一个解释 谢谢你。

我尝试执行以下操作:

final.map(array => array.forEach(array => {
array.reduce((prev,curr)=>{
return {name:prev.name, amount:prev.amount+curr.amount}
})
}))

0 个答案:

没有答案