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

后端 未结 5 1998
误落风尘
误落风尘 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: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);

提交回复
热议问题