I'm working with Vue and Rails. The goal of the code below is remove text from input fields when users toggle between adding a new recipe and going back to the main page. This works with all my fields except for ingredients.
Ingredients is an array that belongs to the recipe object and holds a name in a key value pair. I want to loop through this and remove all the ingredients. I do that by calling the removeIngredients function. The problem is when I execute the code below, the loop only grabs every other index and thus only half of the ingredients are deleted.
resetNewRecipe: function(){
this.recipe.name = '';
this.recipe.chef = '';
this.recipe.cooktime = '';
this.recipe.amount = '',
this.recipe.description = '';
this.recipe.favorite = false;
this.recipe.ingredients.name = '';
for (i = 0; i < this.recipe.ingredients.length; i++){
for (var name in this.recipe.ingredients[i]){
if (this.recipe.ingredients[i].hasOwnProperty(name)){
console.log("name = " + name);
console.log("i = " + i);
console.log("this.recipe.ingredients[i][name] " + this.recipe.ingredients[i][name]);
this.removeIngredient(i);
}
}
}
},
The recipe object code
recipe: {
name: '',
chef: '',
cooktime: '',
amount: '',
description: '',
favorite: false,
ingredients: [
{name: ''},
]}
Console.log returns when I create four ingredients each named 1,2,3,4. Basically 1 and 3 get passed successfully and are deleted, while 2 and 4 remain when I return back to the form.
name = name
i = 0
this.recipe.ingredients[i][name] 1
name = name
i = 1
this.recipe.ingredients[i][name] 3
this.recipes.ingredients = []instead of looping through each since you just want to reset the object?