考慮兩個物件陣列:
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中文網其他相關文章!