Javascript: Merge Objects By Key
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, anotherValue: 15}
Solution 1:
try this:
functionmergeById(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]
}
});
returnObject.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)))
Post a Comment for "Javascript: Merge Objects By Key"