如何在es6中增加相似对象键的值

时间:2018-09-13 08:44:07

标签: javascript ecmascript-6

就像这是我的对象数组:

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上执行此操作

1 个答案:

答案 0 :(得分:0)

使用 //Add items ... //Print property from particular index Console.WriteLine(l1[index].propertyname); reduce是一种数组方法,可以将数组转换为其他数组,即可以具有不同长度的另一个数组。 reduce将始终返回具有相同数量元素的数组。并且map可以返回一个元素较少的数组,但是元素将保持不变。

减少为您提供更灵活的行为。您可以更改元素,也可以以任何喜欢的方式存储它们。

filter

如果此代码经常在大型数组上运行,则可以使用性能更高但更复杂的解决方案,其中我们使用哈希表来存储数据:

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);

但是在开始优化之前,您应该始终通过运行性能工具来检查是否值得这样做。