concat array of objects javascript using ES-6

Concat Arrays of Objects in JavaScript using ES-6

If you have multiple arrays containing objects and you want to merge them into a single array of objects, you can use the concat method. In ES-6, you can use the spread operator to make your code simpler and more efficient.

Using the Concat Method

The concat method is a built-in method in JavaScript that is used to merge two or more arrays into a single array. Here's an example:


const arr1 = [{name: 'John', age: 30}, {name: 'Mary', age: 25}];
const arr2 = [{name: 'Bob', age: 40}, {name: 'Jane', age: 35}];
const arr3 = arr1.concat(arr2);
console.log(arr3);

In this example, we have three arrays (arr1, arr2, and arr3). We are using the concat method to merge arr1 and arr2 into arr3. The resulting array contains all the elements in arr1 and arr2.

Using the Spread Operator (ES-6)

In ES-6, you can use the spread operator to achieve the same result as the concat method, but with less code. Here's an example:


const arr1 = [{name: 'John', age: 30}, {name: 'Mary', age: 25}];
const arr2 = [{name: 'Bob', age: 40}, {name: 'Jane', age: 35}];
const arr3 = [...arr1, ...arr2];
console.log(arr3);

In this example, we are using the spread operator (...) to merge arr1 and arr2 into arr3. The resulting array contains all the elements in arr1 and arr2.

Conclusion

Concatenating arrays of objects in JavaScript is easy using either the concat method or the spread operator in ES-6. Both methods achieve the same result, but the spread operator is more concise and efficient.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe