js 合并数组对象中的相同项,并统计数量和
let list=[
{
id:11,
name:'apple',
num:2
},
{
id:11,
name:'apple',
num:3
},
{
id:22,
name:'pig',
num:2
},
{
id:11,
name:'apple',
num:2
},
]
list = list.reduce((obj, item) => {
let find = obj.find(i => i.id === item.id)
let _d = {
...item,
frequency: 1
}
find ? (find.num+=item.num,find.frequency++ ): obj.push(_d)
return obj
}, [])
输出=>
[
{
id: 11,
name: "apple",
frequency:3,
num: 7
},{
id: 22,
name: "pig",
frequency:1,
num: 2,
}
]