0

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
1
  • 1
    why not just this.recipes.ingredients = [] instead of looping through each since you just want to reset the object? Commented Feb 25, 2017 at 23:39

1 Answer 1

1

Iterate backwards through the array, so from the last index to 0. That way you will get to delete them all. Also, you should break out of the inner loop when you actually delete one:

for (var i = this.recipe.ingredients.length - 1; i >= 0; i--){ // <-- change direction
  for (var name in this.recipe.ingredients[i]){
    if (this.recipe.ingredients[i].hasOwnProperty(name)){
      this.removeIngredient(i);
      break; // <------ add this
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

That did it. Thank you so much for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.