I'm currently facing an issue with my function that adds objects to an array. The problem arises when a key value already exists in the array - it still gets added again, but I want it to only add if it doesn't exist yet. Here's what I have:
onCheckRecipe(e) {
if (e.detail.checked === true) {
let tickedRecipe = e.detail.value;
let foundRecipeIngredients = [];
let foundRecipe;
this.loadedRecipes.filter(function (el) {
if (el._id === tickedRecipe) {
el.ingredients.map((elm) => {
foundRecipe = elm;
foundRecipeIngredients.push(foundRecipe);
});
}
});
this.groceryListUpdated = foundRecipeIngredients;
this.groceryListDefault = this.groceryListDefault.concat(
this.groceryListUpdated
);
}
}
In the console, I see something like this:
(12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {name: "", quantity: ""}
1: {_id: "5f64ac1eb227fea1f63a5ca3", name: "avocado", quantity: "50g"}
2: {_id: "5f64ac1eb227fea1f63a5ca4", name: "lemon juice", quantity: "5g"}
3: {_id: "5f64ac1eb227fea1f63a5ca5", name: "small mozzarella pearls", quantity: "70g"}
4: {_id: "5f64ac1eb227fea1f63a5c9e", name: "almond flour", quantity: "10g"}
5: {_id: "5f64ac1eb227fea1f63a5c9f", name: "egg", quantity: "10g"}
6: {_id: "5f64ac1eb227fea1f63a5ca0", name: "unsalted butter", quantity: "30g"}
7: {_id: "5f64ac1eb227fea1f63a5ca1", name: "peanut butter", quantity: "50g"}
8: {_id: "5f64ac1eb227fea1f63a5c99", name: "chia seeds", quantity: "10g"}
9: {_id: "5f64ac1eb227fea1f63a5c9a", name: "cherries", quantity: "15g"}
10: {_id: "5f64ac1eb227fea1f63a5c9b", name: "honey", quantity: "30g"}
11: {_id: "5f64ac1eb227fea1f63a5c9c", name: "almond flour", quantity: "10g"}
length: 12
__proto__: Array(0)
My goal is to avoid adding something like "almond flour" twice if it already exists in the array, and only update the quantity. I've tried various methods without success. Any insights or ideas would be greatly appreciated. Thank you.