1 var data = [ 2 {"Networking": "WiFi", "count_value": "2000"}, 3 {"Networking": "WiFi", "count_value": "2890"}, 4 {"Networking": "WiFi", "count_value": "2900"}, 5 {"Networking": "CellNetwork", "count_value": "3010"}, 6 {"Networking": "CellNetwork", "count_value": "3000"} 7 ]; 8 //现在想要把Networking中都为Wifi和CellNetwork的count_value合并 9 var obj = {}; 10 for (var i in data) { 11 if (obj[data[i].Networking]) { 12 obj[data[i].Networking].value = Number(obj[data[i].Networking].value) + Number(data[i].count_value); 13 } else { 14 obj[data[i].Networking] = { 15 value: data[i].count_value 16 } 17 } 18 }
//结果
console.log(JSON.stringify(obj));
{"WiFi":{"value":7790},"CellNetwork":{"value":6010}}
for (var i in obj) { console.log(i); console.log(obj[i].value) } //结果为: WiFi 7790 // CellNetwork 6010