Search code examples
javascriptarraysjavascript-objects

Merge two arrays of objects with the same keys in JavaScript


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.

Solution

  • 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]);