aleksey080
aleksey080

Reputation: 187

Sum properties child objects with lodash

I use lodash in my project. I have a JSON

 { arcade: {
    sam: {
        played: 10,
        wins: 5,
        lose: 5
      },
     adam: {
       played: 10,
       wins: 5,
       lose: 5
     },
  }

  pvp: {
    sam: {
        played: 10,
        wins: 5,
        lose: 5
      },
     adam: {
       played: 10,
       wins: 5,
       lose: 5
     },
  }
}

I would like to receive as a result of JSON

{
  arcade: {
    played: 20,
    wins: 10,
    lose: 10
  },
  pvp: {
    played: 20,
    wins: 10,
    lose: 10
  },
}

how to calculate the sum of values child objects with js/lodash? Thanks.

Upvotes: 2

Views: 9921

Answers (1)

ChinKang
ChinKang

Reputation: 4342

http://jsfiddle.net/efmmh8ok/
I would use reduce function (lodash doc)

 _.reduce(ori, function (ori1, data1, c) {
    ori1[c] = _.reduce(data1, function (ori2, data2) {
        _.each(data2, function (value, key) {
            ori2[key] = ori2[key] || 0; // if it undefined yet put number 0 
            ori2[key] += value; // sum with the previous value
        });
        return ori2; // the populated data {played: 20, wins: 10, lose: 10}
    }, ori1[c] || {});
    return ori1; // the populated data {pvp: {played: 20, wins: 10, lose: 10}}
}, {});

Upvotes: 2

Related Questions