我正在创建一个基于食谱的购物车。
this.shoppingCartRecipes.forEach(recipe => {
recipe.ingredients.forEach(ingredient => {
this.shoppingCart.push({
amount: ingredient.amount,
unit: ingredient.unit,
name: ingredient.ingredient,
isDone: ingredient.isDone || false,
recipeID: recipe.id
});
});
});但是,如果配料名称和配料单位相同,我希望合并这些值。有没有一种聪明的方法可以做到这一点?
发布于 2019-06-12 23:40:36
如果将this.shoppingCart保留为数组:
this.shoppingCartRecipes.forEach(recipe => {
recipe.ingredients.forEach(ingredient => {
const shoppingCartIngredient = this.shoppingCart.find( item => (
(item.name === ingredient.ingredient) && (item.unit === ingredient.unit)
))
// If the ingredient exists, just update it
if (shoppingCartIngredient) {
shoppingCartIngredient.amount = ingredient.amount;
shoppingCartIngredient.isDone = ingredient.isDone || false;
shoppingCartIngredient.recipeID = recipe.id;
} else {
// Otherwise create a new record
this.shoppingCart.push({
amount: ingredient.amount,
unit: ingredient.unit,
name: ingredient.ingredient,
isDone: ingredient.isDone || false,
recipeID: recipe.id
});
}
});
});发布于 2019-06-12 23:30:52
您可以使用` `lodash‘库:
推流后使用_.uniq(array);或_.uniqBy(array);。
https://stackoverflow.com/questions/56565657
复制相似问题