Merge JSON Object with same “key” and add their “value” using JavaScript

后端 未结 5 1995
误落风尘
误落风尘 2021-02-06 19:07

My JSON looks like this

{\"rows\":[
    {\"key\":[\"zeit.de\"],\"value\":98},
    {\"key\":[\"google.com\"],\"value\":49},
    {\"key\":[\"spiegel.de\"],\"value\         


        
5条回答
  •  孤城傲影
    2021-02-06 19:31

    you can use lodash

    let result = [{'a': 3, 'b': 2}, {'a': 4, 'c': 1}, {'a': 4, 'c': 1}];
    let m = _.reduce((_.uniq(_.flattenDeep(_.map(result, i => _.keys(i))))), function (s, v) {
        s[v] = _.sumBy(result, function (o) {
            return o[v];
        });
        return s
    }, {});
    
    console.log(m); // { a: 11, b: 2, c: 2 }
    

提交回复
热议问题