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,
}
]

WX20210922-091703.png

posted @ 2020-03-20 09:45  王志超II  阅读(3952)  评论(0编辑  收藏  举报