Skip to content
the poor coder

concat array of objects javascript using ES-6

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC