Group By and Sum using Underscore/Lodash

后端 未结 6 2071
鱼传尺愫
鱼传尺愫 2020-12-09 04:44

I have JSON like this:

[
  {
     platformId: 1,
     payout: 15,
     numOfPeople: 4
  },
  {
     platformId: 1,
     payout: 12,
     numOfPeople: 3

  }         


        
6条回答
  •  误落风尘
    2020-12-09 05:24

    You can do this without Underscore:

    var result = data.reduce(function(acc, x) {
      var id = acc[x.platformId]
      if (id) {
        id.payout += x.payout
        id.numOfPeople += x.numOfPeople
      } else {
        acc[x.platformId] = x
        delete x.platformId
      }
      return acc
    },{})
    

    But why would you want an object with numeric keys? You could convert it back to a collection:

    var toCollection = function(obj) {
      return Object.keys(obj)
        .sort(function(x, y){return +x - +y})
        .map(function(k){return obj[k]})
    }
    
    toCollection(result)
    

    Note that objects are mutated, so you may to clone them first if you want to maintain the original data.

提交回复
热议问题