javascript - 如何在 es6 中添加相似对象键的值
问题描述
就像这是我的对象数组:
var x = [
{_id: 1, total: 25},
{_id: 1, total: 22},
{_id: 2, total: 4},
{_id: 2, total: 32},
{_id: 3, total: 56},
{_id: 4, total: 21},
{_id: 4, total: 58},
]
现在我想像这样实现类似对象键的所有总和
[
{_id: 1, total: 47},
{_id: 2, total: 36},
{_id: 3, total: 25},
{_id: 4, total: 79},
]
任何人都可以建议如何在 es6 上执行此操作
解决方案
使用reduce
. reduce
是一种数组方法,可以将一个数组转换成别的东西,即另一个可以有不同长度的数组。map
将始终返回具有相同数量元素的数组。并且filter
可以返回一个元素较少但元素不变的数组。
Reduce 为您提供更灵活的行为。您可以更改元素并以您喜欢的任何方式存储它们。
const result = x.reduce((acc, el) => {
const index = acc.findIndex(({_id}) => el._id === _id);
if (index > -1) {
acc[index].total += el.total;
} else {
acc.push({...el});
}
return acc;
}, [])
console.log(result);
如果此代码经常在大型数组上运行,您可以使用性能更高但更复杂的解决方案,我们使用哈希表来存储数据:
var x = [
{_id: 1, total: 25},
{_id: 1, total: 22},
{_id: 2, total: 4},
{_id: 2, total: 32},
{_id: 3, total: 56},
{_id: 4, total: 21},
{_id: 4, total: 58},
]
const temp = {};
for (const el of x) {
temp[el._id] = (temp[el._id] || 0) + el.total;
}
const result = Object.entries(temp).map(([_id, total]) => ({_id, total}));
console.log(result);
但是在开始优化之前,您应该始终通过运行 perf 工具检查是否值得这样做。