考慮以下物件數組:
objArr = [ {key:"Mon Sep 23 2013 00:00:00 GMT-0400", val:42}, {key:"Mon Sep 24 2013 00:00:00 GMT-0400", val:78}, {key:"Mon Sep 25 2013 00:00:00 GMT-0400", val:23}, {key:"Mon Sep 23 2013 00:00:00 GMT-0400", val:54}, // <- duplicate key ]
我們的目標是合併重複的鍵和將它們各自的值相加,得到:
reducedObjArr = [ {key:"Mon Sep 23 2013 00:00:00 GMT-0400", val:96}, {key:"Mon Sep 24 2013 00:00:00 GMT-0400", val:78}, {key:"Mon Sep 25 2013 00:00:00 GMT-0400", val:23} ]
雖然初始嘗試可能涉及迭代和推送值,更有效的方法涉及利用JavaScript內建的函數:
// Use a Map to count values with the same key const counts = objArr.reduce((prev, curr) => { let count = prev.get(curr.key) || 0; prev.set(curr.key, curr.val + count); return prev; }, new Map()); // Convert the Map back to an array of objects const reducedObjArr = [...counts].map(([key, value]) => { return {key, value}; });
此方法將陣列簡化為 Map,其中鍵代表重複的鍵值,值代表它們的總和。然後,地圖將轉換回物件數組以提高可讀性。
以上是如何有效地將 JavaScript 物件與匹配的鍵合併並求和它們的值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!