My JSON looks like this
{\"rows\":[
{\"key\":[\"zeit.de\"],\"value\":98},
{\"key\":[\"google.com\"],\"value\":49},
{\"key\":[\"spiegel.de\"],\"value\
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);