在JavaScript 中使用共享鍵求和物件屬性值
考慮以下JavaScript 物件陣列:
const 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 ];
考慮以下JavaScript 物件陣列:
const 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}, ];
let counts = objArr.reduce((prev, curr) => { let count = prev.get(curr.key) || 0; prev.set(curr.key, curr.val + count); return prev; }, new Map()); let reducedObjArr = [...counts].map(([key, value]) => { return {key, value}; });
以上是如何在 JavaScript 中使用共享鍵求和物件屬性值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!