Merging Objects by Id in JavaScript
In JavaScript, objects can be effectively merged to combine data from multiple sources. When dealing with arrays of objects, a common challenge is to merge objects by a specific field, often referred to as an id.
For instance, given the following arrays:
var a1 = [{ id: 1, name: "test"}, { id: 2, name: "test2"}]; var a2 = [{ id: 1, count: "1"}, {id: 2, count: "2"}];
we want to combine them based on the 'id' field, resulting in the following:
var a3 = [{ id: 1, name: "test", count: "1"}, { id: 2, name: "test2", count: "2"}];
Solution:
A concise and effective solution in ES6 is to utilize the native map function:
const a3 = a1.map(t1 => ({...t1, ...a2.find(t2 => t2.id === t1.id)}));
Here, we iterate through each object t1 in a1 and create a new object. Using the spread operator (...), we spread the properties from t1 into the new object.
To append properties from the matching object in a2, we use the find method to locate the object with the matching 'id'. We then spread the properties from this found object into the new object.
This approach elegantly combines data from the two arrays, producing the desired result. It is also extendable to handle more complex scenarios seamlessly.
The above is the detailed content of How to Merge JavaScript Objects by ID?. For more information, please follow other related articles on the PHP Chinese website!