0

I have two array objects & wanted to merge these.But for some reason it gets inserted one level below of first array

let first = [{name:'a'},{name:'b'}];
let first2 = [{name:'aa'},{name:'bb'}];
first.push(first2);

now if I print first object, it gives below output

[{name: "a"},{name: "b"},[ {name: "aa"}, {name: "bb"}]]

whereas I need this output[ {name: "a"}, {name: "b"}, {name: "aa"}, {name: "bb"}]

Vini
  • 29
  • 7

3 Answers3

2

Spread the first2 array to push the items instead of the whole array:

let first = [{name:'a'},{name:'b'}];
let first2 = [{name:'aa'},{name:'bb'}];
first.push(...first2);

console.log(first);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

I know you asked about .push(), but another way that I prefer to use in these situations is the .concat() method. One potential advantage to using .concat() is that you don't modify first or first2, instead creating a new array. This is useful if you are programming in a functional & immutable style for libraries such as Redux.

let first = [{name:'a'},{name:'b'}];
let first2 = [{name:'aa'},{name:'bb'}];
let both = [].concat(first, first2);

console.log(both);
borrascador
  • 575
  • 1
  • 5
  • 13
0

The problem is you're pushing an array, into another array. .push() adds an item into an array, so it treats the entire array as one item.

The easiest thing to do is to follow this solution, or use the new ES6 spread syntax, that @Ori points out in his answer:

let first = [{name:'a'},{name:'b'}];
let first2 = [{name:'aa'},{name:'bb'}];
first.push.apply(first, first2);

console.log(first);
Blue
  • 22,608
  • 7
  • 62
  • 92