Home >Web Front-end >JS Tutorial >How Can I Efficiently Merge Two Arrays of Objects Based on a Common Key?
Consider two arrays of objects:
Array 1: [ { id: "abdc4051", date: "2017-01-24" }, { id: "abdc4052", date: "2017-01-22" } ]
Array 2: [ { id: "abdc4051", name: "ab" }, { id: "abdc4052", name: "abc" } ]
To merge these arrays based on the id property, a concise solution is to leverage the map() function and Object.assign().
Utilizing map(), we iterate through Array 1. For each object, we create a new object that combines the properties of both objects at the same index in Array 1 and Array 2. This new object is stored in arr3.
let arr1 = [ { id: "abdc4051", date: "2017-01-24" }, { id: "abdc4052", date: "2017-01-22" } ]; let arr2 = [ { id: "abdc4051", name: "ab" }, { id: "abdc4052", name: "abc" } ]; let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i])); console.log(arr3);
This achieves the desired result:
[ { id: "abdc4051", date: "2017-01-24", name: "ab" }, { id: "abdc4052", date: "2017-01-22", name: "abc" } ]
The above is the detailed content of How Can I Efficiently Merge Two Arrays of Objects Based on a Common Key?. For more information, please follow other related articles on the PHP Chinese website!