最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Merge JSON Object with same "key" and add their "value" using JavaScript - Stack Overflow

programmeradmin2浏览0评论

My JSON looks like this

{"rows":[
    {"key":["zeit.de"],"value":98},
    {"key":["google"],"value":49},
    {"key":["spiegel.de"],"value":20},
    {"key":["spiegel.de"],"value":12},
    {"key":["spiegel.de"],"value":20},
    {"key":["spiegel.de"],"value":12},
    {"key":["netmng"],"value":49},
    {"key":["zeit.de"],"value":300}
]}

and I am looking for a solution to merge all the same keys and add the values of the merged keys together to get something looking like this.

{"rows":[
    {"key":["zeit.de"],"value":398},
    {"key":["google"],"value":49},
    {"key":["spiegel.de"],"value":54},
    {"key":["netmng"],"value":49}
]}

Thanks for answersing.

My JSON looks like this

{"rows":[
    {"key":["zeit.de"],"value":98},
    {"key":["google."],"value":49},
    {"key":["spiegel.de"],"value":20},
    {"key":["spiegel.de"],"value":12},
    {"key":["spiegel.de"],"value":20},
    {"key":["spiegel.de"],"value":12},
    {"key":["netmng."],"value":49},
    {"key":["zeit.de"],"value":300}
]}

and I am looking for a solution to merge all the same keys and add the values of the merged keys together to get something looking like this.

{"rows":[
    {"key":["zeit.de"],"value":398},
    {"key":["google."],"value":49},
    {"key":["spiegel.de"],"value":54},
    {"key":["netmng."],"value":49}
]}

Thanks for answersing.

Share asked Jun 14, 2015 at 18:43 marenz2569marenz2569 231 gold badge1 silver badge4 bronze badges 1
  • Loop over the object and load the items into a new object by key using += to add the new value to the previous one. – Leeish Commented Jun 14, 2015 at 18:46
Add a ment  | 

5 Answers 5

Reset to default 4

var json = '{"rows":[{"key":["zeit.de"],"value":98},{"key":["google."],"value":49},{"key":["spiegel.de"],"value":20},{"key":["spiegel.de"],"value":12},{"key":["spiegel.de"],"value":20},{"key":["spiegel.de"],"value":12},{"key":["netmng."],"value":49},{"key":["zeit.de"],"value":300}]}';
var obj = JSON.parse(json);

var newObj = {};
for(i in obj['rows']){
 var item = obj['rows'][i];
    if(newObj[item.key[0]] === undefined){
        newObj[item.key[0]] = 0;
    }
    newObj[item.key[0]] += item.value;
}

var result = {};
result.rows = [];
for(i in newObj){
    result.rows.push({'key':i,'value':newObj[i]});
}
console.log(result);

https://jsfiddle/s8rp84qc/

Here's an alternate solution using ECMA-Script Array functions forEach, some and filter:

var data = {
  "rows": [{
    "key": ["zeit.de"],
    "value": 98
  }, {
    "key": ["google."],
    "value": 49
  }, {
    "key": ["spiegel.de"],
    "value": 20
  }, {
    "key": ["spiegel.de"],
    "value": 12
  }, {
    "key": ["spiegel.de"],
    "value": 20
  }, {
    "key": ["spiegel.de"],
    "value": 12
  }, {
    "key": ["netmng."],
    "value": 49
  }, {
    "key": ["zeit.de"],
    "value": 300
  }]
};

var merged = {
  rows: []
};

data.rows.forEach(function(sourceRow) {
  debugger;
  if(!merged.rows.some(function(row) { return row.key[0] == sourceRow.key[0]; })) {
    merged.rows.push({ key: [sourceRow.key[0]], value: sourceRow.value });
  } else {
    var targetRow = merged.rows.filter(function(targetRow) { return targetRow.key[0] == sourceRow.key[0] })[0];
    
    targetRow.value += sourceRow.value;
  }
});

document.getElementById("result").textContent = JSON.stringify(merged);
<div id="result"></div>

You can try something like this:

var newData = {rows: []},
    index;

for (var i = 0; i < data.rows.length;i++){
    index = newDataContains(data.rows[i].key);
    if (index == -1){
        newData.rows.push({key: data.rows[i].key, value: data.rows[i].value});
    } else {
        newData.rows[index].value += data.rows[i].value;
    }
}

function newDataContains(key){
    for (var i=0; i < newData.rows.length; i++){
        if (JSON.stringify(newData.rows[i].key) == JSON.stringify(key)) {
            return i;
            break;
        }
    }
    return -1;
}

jsfiddle: https://jsfiddle/9p81g5j6/

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 }

JSON look like below: 2 scenario Url is mon When pass the role -id

  1. role- id/name has admin:

    [{"Key":"value1"},{"key":"value2"},{"key":"value3"}]
    
  2. role- id/name has Tester

    [{"Key":"value1"},{"key":"value3"}]
    

no key:value2 is there for Tester

For example:

Global variable string a, b;

wants to take all of the values from the key-value Pair if it has value2 and value3 from the JSON

i.e.: admin go for a="both"

check Tester if it has only value3 then b="single"

发布评论

评论列表(0)

  1. 暂无评论