I have an array of objects that looks like this:
var countries = [
{id: SWE, value: 5},
{id: DE, value:10},
{id: SWE, anotherValue: 11},
{id: DE
try this:
function mergeById(a){
var obj={};
a.forEach(function(e){
if(e && e.id){
obj[e.id] = obj[e.id] || {};
for(var _k in e) obj[e.id][_k] = e[_k]
}
});
return Object.keys(obj).map(function (key) {return obj[key]});
}
var countries = [
{id: 'SWE', value: 5},
{id: 'DE', value:10},
{id: 'SWE', anotherValue: 11},
{id: 'DE', anotherValue: 15}
]
document.write(JSON.stringify(mergeById(countries)))