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}
]

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.

Answers:

Answer

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)))

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.