[英]Count duplicates and order them in array of objects Javascript
我有以下對象數組:
[ { id: 1, someOtherStuff: 'abc, Drink: { name: 'Coca-Cola', price: 2.5 } }, { id: 2, someOtherStuff: 'def, Drink: { name: 'Fanta Orange', price: 3 } }, { id: 3, someOtherStuff: 'ghi, Drink: { name: 'Sprite', price: 1.8 } }, { id: 6, someOtherStuff: 'jkl, Drink: { name: 'Coca-Cola', price: 2.5 } }, { id: 7, someOtherStuff: 'mno, Drink: { name: 'Coca-Cola', price: 2.5 } } ]
我想通過這樣的重復項對它們進行分組:
[ { count: 3, drinkName: 'Coca-Cola', price: 2.5 }, { count: 1, drinkName: 'Fanta Orange', price: 3 }, { count: 1, drinkName: 'Sprite', price: 1.8 } ]
我嘗試了幾種方法來映射一個新數組。但不幸的是我無法讓它工作
我希望有人可以幫助我
let result= {};
inputArray.map((item)=>{
let key = `${item.Drink.name}-${item.Drink.price}`;
if(result[key]){
result[key].count = result[key].count +1;
}else{
result[key] = {count:1,drinkName:item.Drink.name,price:item.Drink.price};
}
});
result = Object.values(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.