-1

I would like to merge these two arrays

const arr1 = [{ label: 'one', value: 'one', type: 'arr1'}];
const arr2 = [{ label: 'two', value: 'two', type: 'arr1'}];

to get the following result

const arr3 = [{ label: 'one', value: 'one' type: 'arr1'}, { label: 'two', value: 'two' type: 'arr1'}];

I've tried arr1.concat(arr2) and _.merge(arr1, arr2) and [arr1, arr2] and get the following error

TypeError: Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.
8245734589
  • 47
  • 5
  • 6
    You're missing a comma before `type` making it an invalid syntax – Reyno Oct 21 '21 at 09:27
  • 2
    If you fix the syntax error, you won't get the error message (at least not with `.conat()` and `[arr1, arr2]`). So... -> [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) -> [mcve] – Andreas Oct 21 '21 at 09:29
  • In my code I have the comma, just a mistake when I was writing some dummy code for this question. Thanks for point it out. – 8245734589 Oct 21 '21 at 09:30
  • Does this answer your question? [Merge 2 arrays of objects](https://stackoverflow.com/questions/7146217/merge-2-arrays-of-objects) – Anurag Srivastava Oct 21 '21 at 09:37

3 Answers3

2

Your third try [arr1, arr2] was really close to a right answer, you can use the new spread syntax (...) to concat the arrays by doing to following:

const arr1 = [{ label: "one", value: "one", type: "arr1" }];
const arr2 = [{ label: "two", value: "two", type: "arr1" }];

console.log([...arr1, ...arr2]);
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Markiesch
  • 721
  • 3
  • 11
1

You can try this code it works fine :

 const arr1 = [{ label: 'one', value: 'one', type: 'arr1'}];
        const arr2 = [{ label: 'two', value: 'two', type: 'arr1'}];
        const arr3 = arr1.concat(arr2);
        
        console.log(arr3);
Houssem TRABELSI
  • 782
  • 1
  • 5
  • 11
0

You missed comma before type

But you can solve it that way.

const arr1 = [{ label: 'one', value: 'one', type: 'arr1'}];
const arr2 = [{ label: 'two', value: 'two', type: 'arr1'}];

const arr3 = arr1.concat(arr2);

console.log(arr3);
VLAZ
  • 26,331
  • 9
  • 49
  • 67