js 数组里对象根据属性合并

比如有一个数组

let arr = [

{name:'aaa',num:1},
{name:'aaa',num:2},
{name:'aaa',num:3},

{name:'bbb',num:4},
{name:'bbb',num:5},
{name:'bbb',num:6},

{name:'ccc',num:7},
{name:'ccc',num:8},
{name:'ccc',num:9}

]

我们希望得到  

[

  {name:'aaa',sum:6},      //sum是所有num相加的值

  {name:'bbb',sum:15},

  {name:'bbb',sum:24},

]

//第一步,先给原数组分类,用reduce  

const result = arr.reduce((a,b)=>{
if(a[b.name]){    //根据name分类
a[b.name].push(b)
}else{
a[b.name] = [b]
}
return a
},{})

console.log(result)

//打印会得到  result 如下

{

  aaa:[{name:'aaa',num:1},{name:'aaa',num:2},{name:'aaa',num:3}],

  bbb:[{name:'bbb',num:4},{name:'bbb',num:5},{name:'bbb',num:6}],

  ccc:[{name:'ccc',num:7},{name:'ccc',num:8},{name:'ccc',num:9}]

}

 

//我们操作result对象 

let resultArr = []           for (const key in result) {           let obj = {}        let sum= 0        result[key].forEach(item=>{                   sum += Number(item.num)                               })   obj.name = result[key][0].name        obj.sum= sum        resultArr .push(obj) }
//打印resultArr 即可得到 console.log(resultArr )

[

  {name:'aaa',sum:6},      

  {name:'bbb',sum:15},

  {name:'bbb',sum:24},

]

 

 

上一篇:Nginx列目录文件


下一篇:华为交换机开启ftp服务,上传和下载文件,get和put操作