Join an array of objects

I need to combine arrays of objects in a javascript browser as follows:

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

-> new data arrive

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

It’s good that simplified arrays will contain hundreds of large objects. Therefore, I need a solution for performers.

Thank you in advance for your skeec

+4
source share
4 answers

It seems you can just use .push()or .concat()to combine the two arrays. It does not matter what is in the arrays, since the array operators simply abstractly process the elements of the array, not knowing what is in them.

Here is a solution that adds a new array to an 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);

, ( ), :

data.push.apply(data, newInfo);
+4

, , 2 , , .

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

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

var concatArr = arr1.concat(arr2);

MDN Array.prototype.concat

+3
var arr3 = [];
for(var i in arr1){
   var shared = false;
   for (var j in arr2)
       if (arr2[j].name == arr1[i].name) {
           shared = true;
           break;
       }
   if(!shared) arr3.push(arr1[i])
}
arr3 = arr3.concat(arr2);
0
source

You can use loadash for this:

Something like that:

var array = [1];
var other = _.concat(array, 2, [3], [[4]]);

console.log(other);
// → [1, 2, 3, [4]]

console.log(array);
// → [1]

Or for Json, you can use the extension as follows:

lodash.extend({}, mergeInto, toMerge)
0
source

All Articles