如何计算的属性值对象的出现,并存储在新的数组对象计数

问题描述 投票:1回答:1

我要统计有多少次相同的值对象内发生,且与添加量,创建新的对象。

我一直在使用filtermapreduce尝试,但没有奏效。

我有这样的数据:

let arrayOfObjects = [
    {name: 'Disney', type: 'inteira'},
    {name: 'Bottieli', type: 'inteira'},
    {name: 'Monster Truck', type: 'inteira'},
    {name: 'Xuxa', type: 'desconto'},
    {name: 'Pokémon', type: 'zaffari'},
]

我想是这样的输出(做一个新的对象,而基于“类型”的键值,并显示每个项目的数量重复项):

newArrayOfObjects = [
    {name: 'Disney', type: 'inteira', quantity: 3},
    {name: 'Xuxa', type: 'desconto', quantity: 1},
    {name: 'Pokémon', type: 'zaffari', quantity: 1}
]
javascript arrays ecmascript-6 counting
1个回答
0
投票

有许多的可以做到这一点的方式。一种方法是通过Array#reduce方法,其中每个type映射到与由包括item数据相应count构造的映射如下(请注意,使用这样的映射是一种优化):

  • 迭代您的输入数组
  • 对于每次迭代,所述输入减少到一个映射,其中映射的key是物品type,并且value是物品(具有计数)
  • 如果type密钥的值在映射被发现,递增匹配项的计数
  • 如果type密钥的值未在映射中找到,插入当前项的克隆被迭代中reduce(),与1的初始计包含该项目的
  • 路过reduce()创建的映射Object.values()提取的物品的平坦Array与减速期间计算对应的计数

这里的工作片段以行动表达这一点:

let arrayOfObjects = [
    {name: 'Disney', type: 'inteira'},
    {name: 'Bottieli', type: 'inteira'},
    {name: 'Monster Truck', type: 'inteira'},
    {name: 'Xuxa', type: 'desconto'},
    {name: 'Pokémon', type: 'zaffari'},
]

/* Iterate arrayOfObjects and reduce() this to a temporary mapping where item counts
are aggregated. Once that mapping is built, we'll extract values of the mapping to
get the desired array result (ie with items, and type counts) */
let newArrayOfObjects = Object.values(arrayOfObjects.reduce((mapping, item) => {
  
  /* Find exsiting item with matching item type in our mapping */
  const { [item.type]:matchingItem } = mapping;
  
  /* If matching item found, increment the count */
  if(matchingItem) {
    matchingItem.count ++;
  }
  /* Otherwise, insert item into mapping, and also include a starting count of one for it */
  else {
    mapping[ item.type ] = { ...item, count : 1 };
  }
  
  /* Return the updated mapping */
  return mapping;

},{}))

console.log(newArrayOfObjects);

希望帮助:-)

© www.soinside.com 2019 - 2024. All rights reserved.