How to group or merge this array of objects in javascript?

前端 未结 8 856
悲&欢浪女
悲&欢浪女 2020-12-18 23:22

I have an array of objects like below for example.

{name: \"Mc Donald\", quantity: 4, maleCount: 1, femaleCount: 0}
{name: \"KFC\", quantity: 9, maleCou         


        
8条回答
  •  清歌不尽
    2020-12-18 23:45

    You can use forEach() loop and add to new array. You can pass empty object as thisArg parameter that you can use as this in your callback function and in second forEach context of this will still be the same as in first callback function because of arrow function.

    var data = [{"name":"Mc Donald","quantity":4,"maleCount":1,"femaleCount":0},{"name":"KFC","quantity":9,"maleCount":1,"femaleCount":0},{"name":"KFC","quantity":9,"maleCount":1,"femaleCount":0},{"name":"Mc Donald","quantity":4,"maleCount":0,"femaleCount":1},{"name":"KFC","quantity":9,"maleCount":0,"femaleCount":1},{"name":"KFC","quantity":9,"maleCount":1,"femaleCount":0},{"name":"KFC","quantity":9,"maleCount":0,"femaleCount":1},{"name":"KFC","quantity":9,"maleCount":0,"femaleCount":1}]
    var result = [], keys = ['quantity', 'maleCount', 'femaleCount']
    
    data.forEach(function(e) {
      if(!this[e.name]) result.push(this[e.name] = e);
      else keys.forEach(k => this[e.name][k] += e[k])
    }, {})
    
    console.log(result)

提交回复
热议问题