Javascript: merge objects by key

試著忘記壹切 提交于 2020-01-30 08:05:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!