考虑两个对象数组:
Array 1: [ { id: "abdc4051", date: "2017-01-24" }, { id: "abdc4052", date: "2017-01-22" } ]
Array 2: [ { id: "abdc4051", name: "ab" }, { id: "abdc4052", name: "abc" } ]
根据以下条件合并这些数组id 属性,一个简洁的解决方案是利用 map() 函数和Object.assign().
利用map(),我们迭代数组1。对于每个对象,我们创建一个新对象,该对象组合了数组1和数组2中同一索引处的两个对象的属性。这个新对象存储在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);
这达到了预期的结果:
[ { id: "abdc4051", date: "2017-01-24", name: "ab" }, { id: "abdc4052", date: "2017-01-22", name: "abc" } ]
以上是如何基于公共键高效合并两个对象数组?的详细内容。更多信息请关注PHP中文网其他相关文章!