Merge JSON Object with same “key” and add their “v

2019-03-22 08:20发布

问题:

My JSON looks like this

{"rows":[
    {"key":["zeit.de"],"value":98},
    {"key":["google.com"],"value":49},
    {"key":["spiegel.de"],"value":20},
    {"key":["spiegel.de"],"value":12},
    {"key":["spiegel.de"],"value":20},
    {"key":["spiegel.de"],"value":12},
    {"key":["netmng.com"],"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.com"],"value":49},
    {"key":["spiegel.de"],"value":54},
    {"key":["netmng.com"],"value":49}
]}

Thanks for answersing.

回答1:

var json = '{"rows":[{"key":["zeit.de"],"value":98},{"key":["google.com"],"value":49},{"key":["spiegel.de"],"value":20},{"key":["spiegel.de"],"value":12},{"key":["spiegel.de"],"value":20},{"key":["spiegel.de"],"value":12},{"key":["netmng.com"],"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.net/s8rp84qc/



回答2:

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

var data = {
  "rows": [{
    "key": ["zeit.de"],
    "value": 98
  }, {
    "key": ["google.com"],
    "value": 49
  }, {
    "key": ["spiegel.de"],
    "value": 20
  }, {
    "key": ["spiegel.de"],
    "value": 12
  }, {
    "key": ["spiegel.de"],
    "value": 20
  }, {
    "key": ["spiegel.de"],
    "value": 12
  }, {
    "key": ["netmng.com"],
    "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>



回答3:

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.net/9p81g5j6/



回答4:

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 }


回答5:

JSON look like below: 2 scenario Url is common 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"