Merging JavaScript Objects by Id
Question:
How can I efficiently merge two JavaScript arrays of objects based on a common "id" property, adding additional data from the second array to the first?
Example:
var a1 = [{ id: 1, name: "test" }, { id: 2, name: "test2" }] var a2 = [{ id: 1, count: "1" }, { id: 2, count: "2" }]
Desired Output:
var a3 = [{ id: 1, name: "test", count: "1" }, { id: 2, name: "test2", count: "2" }]
Solution:
Using ES6, you can achieve this with a concise solution:
const a3 = a1.map(t1 => ({ ...t1, ...a2.find(t2 => t2.id === t1.id) }));
This solution leverages the map() and find() methods:
This method effectively merges the objects in a1 and a2 based on the "id" property, adding any additional properties from a2 to the resulting objects in a3.
The above is the detailed content of How to Efficiently Merge JavaScript Objects by ID?. For more information, please follow other related articles on the PHP Chinese website!