Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge Array of Objects

I need to merge arrays of objects in browserside javascript like this:

[
  {name: "john", age: 10},
  {name: "doe", age: 14}
] 

--> new data arrives

[
  {name: "pete", age: 88},
  {name: "larry", age: 42}
]

should become

[
  {name: "john", age: 10},
  {name: "doe", age: 14}, 
  {name: "pete", age: 88},
  {name: "larry", age: 42}
] 

Well thats simplified the arrays will contain hundreds of larger objects. Therefore I need a performant solution.

Thanks in advance yours skeec

like image 833
Skeec Avatar asked Mar 13 '23 13:03

Skeec


1 Answers

It seems you can just use .push() or .concat() to combine the two arrays. It does not matter what is in the arrays as the array operators just work on the elements of the array abstractly without knowing what's in them.

Here's a solution that adds the new array onto the existing one:

var data = [
  {name: "john", age: 10},
  {name: "doe", age: 14}
]; 


var newInfo = [
  {name: "pete", age: 88},
  {name: "larry", age: 42}
]

data = data.concat(newInfo);

Or, if you really want to keep the original array (not create a new one), you can add the new array onto the end of the original array like this:

data.push.apply(data, newInfo);
like image 182
jfriend00 Avatar answered Mar 21 '23 04:03

jfriend00