merge array of objects javascript
- Published
- Reading time
- 2 min read
- Length
- 369 words
On this page
Merging Array of Objects in Javascript#
As a developer, I have often come across a situation where I need to merge two or more arrays of objects. This could be for various reasons such as combining data from different sources, sorting and filtering data, or simply for displaying data in a more meaningful way.
Method 1: Concatenating Arrays#
One of the simplest ways to merge arrays of objects is to use the concat() method. This method is used to merge two or more arrays and create a new array that contains all the elements from the merged arrays.
const firstArray = [
{id: 1, name: "John"},
{id: 2, name: "Mary"}
];
const secondArray = [
{id: 3, name: "Jane"},
{id: 4, name: "Bob"}
];
const mergedArray = firstArray.concat(secondArray);
console.log(mergedArray);
/* Output: [
{id: 1, name: "John"},
{id: 2, name: "Mary"},
{id: 3, name: "Jane"},
{id: 4, name: "Bob"}
] */Method 2: Using the Spread Operator#
Another way to merge arrays of objects is to use the spread operator (...). This operator allows us to spread the elements of an array into a new array.
const firstArray = [
{id: 1, name: "John"},
{id: 2, name: "Mary"}
];
const secondArray = [
{id: 3, name: "Jane"},
{id: 4, name: "Bob"}
];
const mergedArray = [...firstArray, ...secondArray];
console.log(mergedArray);
/* Output: [
{id: 1, name: "John"},
{id: 2, name: "Mary"},
{id: 3, name: "Jane"},
{id: 4, name: "Bob"}
] */Method 3: Using the Array.reduce() Method#
The reduce() method is used to apply a function to each element of an array and reduce it to a single value. We can also use this method to merge arrays of objects by passing a function that combines the elements of the arrays.
const firstArray = [
{id: 1, name: "John"},
{id: 2, name: "Mary"}
];
const secondArray = [
{id: 3, name: "Jane"},
{id: 4, name: "Bob"}
];
const mergedArray = firstArray.reduce((acc, curr) => [...acc, curr], secondArray);
console.log(mergedArray);
/* Output: [
{id: 1, name: "John"},
{id: 2, name: "Mary"},
{id: 3, name: "Jane"},
{id: 4, name: "Bob"}
] */Conclusion#
These are three simple ways to merge arrays of objects in Javascript. Depending on the use case and the data structure, one method might be more suitable than the others. It is important to choose the appropriate method based on the requirements and constraints of the project.