javascript - Sum properties child objects with lodash - Stack Overflow

I use lodash in my project. I have a JSON{ arcade: {sam: {played: 10,wins: 5,lose: 5},adam: {played: 10

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.

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.

Share Improve this question asked Jan 13, 2015 at 9:41 aleksey080aleksey080 1874 silver badges13 bronze badges 1
  • Do you know how to iterate over objects? – Ja͢ck Commented Jan 13, 2015 at 9:44
Add a ment  | 

1 Answer 1

Reset to default 2

http://jsfiddle/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}}
}, {});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745674464a4639603.html

相关推荐

  • javascript - Sum properties child objects with lodash - Stack Overflow

    I use lodash in my project. I have a JSON{ arcade: {sam: {played: 10,wins: 5,lose: 5},adam: {played: 10

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信