我需要获取一个数组并将具有相同键的所有对象组合在一起,然后将值相加以创建单个对象(如果键匹配)。

这是我的数组示例:

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。

我搜索了与我的特定问题相匹配的答案,但找不到任何答案,如果这是重复的,我深表歉意。许多帖子的问题都很相似,但在大多数情况下,他们需要计算具有相同键、值对的对象,而不是实际添加具有相同键的值。

谢谢!

请您参考如下方法:

您可以使用 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))


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!