如何实现购物清单数组食材去重及数量累加/扣除功能
Grocery List: Fix Ingredient Quantity Accumulation & Removal Logic
I'm working on an Angular grocery list feature with these core requirements:
- When a recipe is checked, add its ingredients to
groceryList: if an ingredient already exists, accumulate its quantity; if not, add it as a new entry - When a recipe is unchecked, subtract the ingredient quantity from
groceryList: if the remaining quantity equals 0 (matches the amount being subtracted), remove the ingredient entirely
Current Code (Initial Attempt)
groceryList = []; ngOnInit() { this._recipesSub = this.recipesService.recipes.subscribe((receivedData) => { this.loadedRecipes = receivedData.recipes; }); } onCheckRecipe(e) { if (e.detail.checked === true) { let tickedRecipe = e.detail.value; let selectedRecipeIngredients; for (let recipe of this.loadedRecipes) { if (recipe.name === tickedRecipe) { selectedRecipeIngredients = recipe.ingredients; } } for (let selectedIng of selectedRecipeIngredients) { for (let existingIng of this.groceryList) { if (selectedIng.name) { this.groceryList.push(selectedIng); } } } console.log(this.groceryList); } }
Current Issue
When I check a recipe, the console shows duplicate ingredient objects (e.g., multiple "almond flour" entries) instead of accumulating their quantities. The quantity merging logic isn't working at all.
Desired Outcome
- For example: two entries of 10g almond flour should combine into a single entry of 20g
- When unchecking a recipe: if the ingredient's current quantity matches the amount being subtracted, remove it from
groceryList; otherwise, reduce the quantity by the recipe's ingredient amount
My Attempt at Fixing the Logic (Including Removal)
onCheckRecipe(e) { if (e.detail.checked === true) { for (let recipe of this.loadedRecipes) { if (recipe.name === e.detail.value) { recipe.ingredients.forEach((eachIngredient) => { let matchedIng = this.groceryList.find(function (foundIng) { return foundIng.name === eachIngredient.name; }); if (matchedIng) { matchedIng.quantity = matchedIng.quantity + eachIngredient.quantity; } else { this.groceryList.push(eachIngredient); } }); } } } else { for (let recipe of this.loadedRecipes) { if (recipe.name === e.detail.value) { recipe.ingredients.forEach((element) => { let matched = this.groceryList.find(function (foundIngre) { return foundIngre.name === element.name; }); if (matched.quantity === element.quantity) { let index = this.groceryList.findIndex( (x) => x.name === matched.name ); this.groceryList.splice(index, 1); } else { matched.quantity = matched.quantity - element.quantity; } }); } } } }
I'm still having issues getting this to work correctly. Could anyone help me refine this logic to meet the requirements?
内容的提问来源于stack exchange,提问作者alex
相关产品推荐
相关产品推荐

