The task is to merge two arrays of objects based on a common key without iterating through their keys.
Consider the following two arrays:
Array 1: [ { id: "abdc4051", date: "2017-01-24" }, { id: "abdc4052", date: "2017-01-22" } ] Array 2: [ { id: "abdc4051", name: "ab" }, { id: "abdc4052", name: "abc" } ]
The goal is to merge these arrays based on the id key to obtain:
[ { id: "abdc4051", date: "2017-01-24", name: "ab" }, { id: "abdc4052", date: "2017-01-22", name: "abc" } ]
To achieve this without iterating through object keys:
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 code uses the Object.assign() method to merge the properties of objects at the same index in both arrays. The result is a new array with the combined properties of both arrays.
The above is the detailed content of How Can I Merge Two Arrays of Objects Based on a Shared Key Without Explicit Key Iteration?. For more information, please follow other related articles on the PHP Chinese website!