How to Merge Multiple Array of Object by ID in JavaScript?
Last Updated :
23 Aug, 2024
Merging multiple arrays of objects by a shared key, like ID, in JavaScript, is used when consolidating data from various sources, such as API responses or databases. This process involves combining objects that have the same key into a single object, allowing developers to manage and manipulate complex datasets more effectively.
Below are different approaches to merge arrays of objects by ID in JavaScript:
Using a Loop and Find Method
In this approach, we manually loop through one array and use the "find" method to search for a matching object in the other array based on a common ID. Once a match is found, the objects are merged into a single object. This method is easy to implement, making it ideal for small datasets. However, it can become inefficient with larger arrays due to the repeated searching within the array for each iteration.
Syntax:
let result = array1.map(obj => {
let matchingObj = array2.find(o => o.id === obj.id);
return matchingObj ? { ...obj, ...matchingObj } : obj;
});
Example : This code combines the users
and preferences
arrays by merging objects with matching id
values, resulting in a unified array with combined properties.
JavaScript
let users = [
{ id: 1, name: 'HTML' },
{ id: 2, name: 'CSS' },
{ id: 3, name: 'JavaScript' }
];
let preferences = [
{ id: 1, popularity: 'High' },
{ id: 2, popularity: 'Medium' }
];
let mergedArray = users.map(user => {
let preference = preferences.find(pref => pref.id === user.id);
return preference ? { ...user, ...preference } : user;
});
console.log(mergedArray);
Output[
{ id: 1, name: 'HTML', popularity: 'High' },
{ id: 2, name: 'CSS', popularity: 'Medium' },
{ id: 3, name: 'JavaScript' }
]
Using reduce Method
The reduce method provides a concise and functional way to merge arrays by accumulating results during iteration. In this approach, reduce iterates over each object in the first array, using find to locate a corresponding object in the second array based on the ID. When a match is found, the two objects are merged and added to the accumulator array. After processing all elements, the final merged array is returned, offering a streamlined solution for combining objects from multiple arrays
Syntax:
let mergedArray = array1.reduce((acc, obj) => {
let matchingObj = array2.find(o => o.id === obj.id);
acc.push(matchingObj ? { ...obj, ...matchingObj } : obj);
return acc;
}, []);
Example: This code uses the reduce
method to merge the users
and preferences
arrays based on matching id
properties, combining objects into a final merged array.
JavaScript
let users = [
{ id: 1, name: 'HTML' },
{ id: 2, name: 'CSS' },
{ id: 3, name: 'JavaScript' }
];
let preferences = [
{ id: 1, popularity: 'High' },
{ id: 2, popularity: 'Medium' }
];
let mergedArray = users.reduce((acc, user) => {
let preference = preferences.find(pref => pref.id === user.id);
acc.push(preference ? { ...user, ...preference } : user);
return acc;
}, []);
console.log(mergedArray);
Output[
{ id: 1, name: 'HTML', popularity: 'High' },
{ id: 2, name: 'CSS', popularity: 'Medium' },
{ id: 3, name: 'JavaScript' }
]
Using map and Object.assign
In this approach, we use the map
method to iterate through the first array and Object.assign
to merge objects. This method is somewhat similar to the first approach but employs a different technique for merging. We use map
to traverse each object in the first array. For each object, the find
method is used on the second array to locate a corresponding object by ID
. Object.assign
then creates a new object by combining the properties of the original object and the matched object, resulting in a merged array.
Syntax:
let mergedArray = array1.map(obj => {
let matchingObj = array2.find(o => o.id === obj.id);
return Object.assign({}, obj, matchingObj);
});
Example: This code uses map
and Object.assign
to merge users
and preferences
arrays by combining objects with matching id
values into a single object.
JavaScript
let users = [
{ id: 1, name: 'HTML' },
{ id: 2, name: 'CSS' },
{ id: 3, name: 'JavaScript' }
];
let preferences = [
{ id: 1, popularity: 'High' },
{ id: 2, popularity: 'Medium' }
];
let mergedArray = users.map(user => {
let preference = preferences.find(pref => pref.id === user.id);
return Object.assign({}, user, preference);
});
console.log(mergedArray);
Output[
{ id: 1, name: 'HTML', popularity: 'High' },
{ id: 2, name: 'CSS', popularity: 'Medium' },
{ id: 3, name: 'JavaScript' }
]
Similar Reads
How to Separate Array of Objects into Multiple Objects in JavaScript ?
In JavaScript, the task of separating an array of objects into multiple objects involves organizing and restructuring data based on specific criteria or properties. This process is often necessary when dealing with datasets that need to be grouped or segmented for easier analysis or manipulation. Th
5 min read
JavaScript - Print Object by id in an Array of Objects
Here are the various methods to print objects by id in an array of objects in JavaScript1. Using Array.filter() MethodThe Array.filter() method, creates a new array containing only the object with the specified ID. JavaScriptconst a = [ { id: 1, name: "Alia" }, { id: 2, name: "Dua" }, { id: 3, name:
3 min read
How to Deep Merge Two Objects in JavaScript ?
Typically, in JavaScript, combining two objects is a commonplace thing to do, but when it involves intricate nesting, deep merging turns out to be necessary, deep merge is the activity of taking the attributes or features from multiple objects (which have nested objects) and creating a new object wi
3 min read
How to Move a Key in an Array of Objects using JavaScript?
The JavaScript array of objects is a type of array that contains JavaScript objects as its elements.You can move or add a key to these types of arrays using the below methods in JavaScript:Table of ContentUsing Object Destructuring and Map()Using forEach() methodUsing for...of LoopUsing reduce() met
5 min read
How to convert a map to array of objects in JavaScript?
A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys. Let us discuss some methods
6 min read
How to compare Arrays of Objects in JavaScript?
In JavaScript, comparing arrays of objects can be more complex than comparing primitive data types. We will discuss different ways to compare arrays of objects effectively, with detailed code examples and explanations.Syntax: Before going to detail the comparison techniques, let's first understand h
5 min read
How to Convert an Object into Array of Objects in JavaScript?
Here are the different methods to convert an object into an array of objects in JavaScript1. Using Object.values() methodObject.values() method extracts the property values of an object and returns them as an array, converting the original object into an array of objects.JavaScriptconst a = { java:
3 min read
How to Convert Object to Array in JavaScript?
In this article, we will learn how to convert an Object to an Array in JavaScript. Given an object, the task is to convert an object to an Array in JavaScript. Objects and Arrays are two fundamental data structures. Sometimes, it's necessary to convert an object to an array for various reasons, such
4 min read
How to Remove Multiple Objects from Nested Array of Objects in JavaScript ?
A nested array of objects is an array of arrays that contain multiple objects as their elements. Removing multiple objects from the nested array of objects in JavaSript can be accomplished in different ways as listed below:Table of ContentUsing filter() with some() methodUsing filter() with includes
7 min read
How to Convert an Array of Objects to Map in JavaScript?
Here are the different methods to convert an array of objects into a Map in JavaScript1. Using new Map() ConstructorThe Map constructor can directly create a Map from an array of key-value pairs. If each object in the array has a specific key-value structure, you can map it accordingly.JavaScriptcon
3 min read