我要统计有多少次相同的值对象内发生,且与添加量,创建新的对象。
我一直在使用filter
,map
和reduce
尝试,但没有奏效。
我有这样的数据:
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}
]
有许多的可以做到这一点的方式。一种方法是通过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);
希望帮助:-)