组合对象数组中的相同键属性值
给定如下所示的 JavaScript 对象数组,我们如何组合通过将对应的值相加来重复键?
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} ]
使用Map和Reduce的解决方案
我们可以利用map和reduce的强大组合,而不是迭代和推送值减少:
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 ]; // Convert data into a Map with reduce const counts = objArr.reduce((prev, curr) => { const count = prev.get(curr.key) || 0; prev.set(curr.key, curr.val + count); return prev; }, new Map()); // Map counts object back to an array const reducedObjArr = [...counts].map(([key, value]) => { return {key, value} }); console.log(reducedObjArr);
这种方法有效地聚合和组合具有相同键的值,从而产生所需的减少数组。
以上是如何对 JavaScript 对象数组中重复键的值求和?的详细内容。更多信息请关注PHP中文网其他相关文章!