问题
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}
]
I want to merge array elements by id. The result should look like this:
countries = [
{id: SWE, value: 5, anotherValue: 11},
{id: DE, value:10, anotherValue:15}
]
Right now, I'm doing this with a for loop and a lot of if and else.
Question: is there any (more elegant) javascript inbuilt functionality to achieve this?
I've tried googling this, the problem is that I'm not sure what to Google for (I'm a javascript newby). Any help is appreciated.
回答1:
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)))
来源:https://stackoverflow.com/questions/33731265/javascript-merge-objects-by-key