Group By and Sum using Underscore/Lodash

后端 未结 6 2053
鱼传尺愫
鱼传尺愫 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:42

    I tried to do this in the functional way, and the result was like this

    console.log(_.chain(data)
        .groupBy("platformId")
        .map(function(value, key) {
            return [key, _.reduce(value, function(result, currentObject) {
                return {
                    payout: result.payout + currentObject.payout,
                    numOfPeople: result.numOfPeople + currentObject.numOfPeople
                }
            }, {
                payout: 0,
                numOfPeople: 0
            })];
        })
        .object()
        .value());
    

提交回复
热议问题