1

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.

8
  • Do you mean an array of objects? countries is currently not a valid object, the objects within it do not have any keys. Commented Nov 16, 2015 at 8:45
  • 1
    Certainly there is no built in JavaScript functionality to do this. You would need a third party library Commented Nov 16, 2015 at 8:46
  • Also you have SW and SWE merging together to make SWE. Please fix your question and we'll take a look. Commented Nov 16, 2015 at 8:46
  • 1
    What happened to the one with ID "SW" ? Or was that supposed to be "SWE"? Please explain your functionality further so that we can help you. It looks like you are finding all the same ID's ( If id: "SW" was supposed to be "SWE" ), and keeping only the largest values? I see no way to do this with built in javascript in any case. you will have to make the code yourself. This isn't a generic enough case for it to be built in. Commented Nov 16, 2015 at 8:47
  • You can do this yourself. Just iterate through the array and combine this object. Commented Nov 16, 2015 at 8:50

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

No if and else. that looks way more elegant than what I've got.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.