合并具有相同 "key" 的 JSON 对象并使用 JavaScript 添加它们的 "value"

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

我的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}
]}

我正在寻找一种解决方案来合并所有相同的键并将合并后的键的值加在一起以获得如下所示的内容。

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

感谢您的回答。

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/

您可以尝试这样的操作:

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/

这是使用 ECMA-Script Array 函数 forEachsomefilter 的替代解决方案:

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>

你可以使用 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 如下所示:2 场景 Url 很常见 当传递角色 -id

  1. 角色- id/name 有管理员:

    [{"Key":"value1"},{"key":"value2"},{"key":"value3"}]
    
  2. 角色- id/name 有测试员

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

没有 key:value2 测试人员

例如:

全局变量字符串a,b;

如果键值对具有来自 JSON

的值 2 和值 3,则想要从键值对中获取所有值

即:管理员 去一个="both"

检查测试仪 如果它只有 value3 那么 b="single"