我正在根据食谱创建购物车。
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
});
});
});
但是,如果成分名称和成分单位相同,我想合并值。有什么聪明的方法吗?
答案 0 :(得分:1)
您可以使用`lodash'库:
在按下后使用_.uniq(array);
或_.uniqBy(array);
。
答案 1 :(得分:1)
如果将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
});
}
});
});