【问题标题】:How to add value of similar objects keys in es6如何在 es6 中添加相似对象键的值
【发布时间】:2019-02-17 23:06:51
【问题描述】:

就像这是我的对象数组:

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

【问题讨论】:

标签: javascript ecmascript-6


【解决方案1】:

使用reducereduce 是一种数组方法,可以将数组转换为其他东西,即另一个可以具有不同长度的数组。 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);

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-04
  • 1970-01-01
相关资源
最近更新 更多