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

后端 未结 5 1997
误落风尘
误落风尘 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:26

    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"

    0 讨论(0)
  • 2021-02-06 19:27

    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>

    0 讨论(0)
  • 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 }
    
    0 讨论(0)
  • 2021-02-06 19:34

    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/

    0 讨论(0)
  • 2021-02-06 19:35

    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/

    0 讨论(0)
提交回复
热议问题