按键合并对象并添加值的Javascript

3

我需要将一个数组中具有相同键的对象合并在一起,并将它们的值相加,生成一个单独的对象(如果键匹配)。请看下面是我所拥有的数组示例:

var arr = [
{type: "2 shlf cart", itemCount: 4},
{type: "2 shlf cart", itemCount: 4},
{type: "5 shlf cart", itemCount: 10}
]

我需要的是:

var arr = [
{type: "2 shlf cart", itemCount: 8},
{type: "5 shlf cart", itemCount: 10}
]

我曾在另一种场景中使用过 reduce 和 map,那时我需要计算数量而不是合并键。

我搜索了一下符合我的特定问题的答案,但没有找到任何东西,如果这是一个重复问题,请原谅。在许多帖子中,类似的问题都出现了,但大多数情况下,它们需要计算具有相同键值对的对象的数量,而不是实际上将具有相同键的值相加。

谢谢!

1个回答

4
你可以使用reduceObject.values 来解决问题:

const arr = [
  {type: "2 shlf cart", itemCount: 4},
  {type: "2 shlf cart", itemCount: 4},
  {type: "5 shlf cart", itemCount: 10}
]

const out = arr.reduce((a, o) => (a[o.type] ? a[o.type].itemCount += o.itemCount : a[o.type] = o, a), {})
console.log(Object.values(out))

当然,如果这看起来太复杂,你总是可以把它写出来以增强可读性:

const arr = [
  {type: "2 shlf cart", itemCount: 4},
  {type: "2 shlf cart", itemCount: 4},
  {type: "5 shlf cart", itemCount: 10}
]

const out = arr.reduce((a, o) => {
  if (a[o.type]) {
    a[o.type].itemCount += o.itemCount  
  } else {
    a[o.type] = o
  }
  return a  
}, {})

console.log(Object.values(out))


1
在编程中,, a 结尾处的意思是什么? - Gibor
3
我将使用逗号运算符。它会评估括号内的每个表达式,并返回最后一个表达式的值,这里的最后一个表达式是累加器。 - Kobe
@Gibor 没问题,每天都能学到新东西 :P 我只是在一个月或两个月前才学会它的,它对于编写一行代码很有用。 - Kobe
完美地工作了!只需要将 Object.values(out) 转换为变量并在我的表格中使用它(单独的项目)。谢谢! - ptrugby4141

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接