How to merge two array objects in ES6?
In ES6, the spread operator (`…`) can be used to merge two array objects. The spread operator transforms an array into a comma-separated sequence of parameters, which can be used in function calls or array merging. Here is an example demonstrating how to merge two array objects using the spread operator:
const arr1 = [1, 2, 3];const arr2 = [4, 5, 6];
const mergedArray = [...arr1, ...arr2];
console.log(mergedArray); // [1, 2, 3, 4, 5, 6]
In the above example, we created two arrays `arr1` and `arr2`, and then merged them into a new array `mergedArray` using the spread operator. The same method can be used to merge arrays of objects. For example:
const objArr1 = [{ id: 1, name: 'John' }];const objArr2 = [{ id: 2, name: 'Jane' }];
const mergedObjArray = [...objArr1, ...objArr2];
console.log(mergedObjArray); // [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]
Note that the spread operator can only be used for shallow copying, meaning the objects in the merged array are still references to the original objects. If you need to deep copy an array of objects, you can use other methods such as `JSON.parse(JSON.stringify(array))` for deep copying.