2017-02-25 6 views
0

私はVueとRailsを使っています。以下のコードの目的は、ユーザーが新しいレシピの追加とメインページへの切り替えを切り替えるときに入力フィールドからテキストを削除することです。これは成分を除いて私のすべてのフィールドで機能します。オブジェクトのJavaScript配列によるループと値の削除

Ingredientsは、レシピオブジェクトに属し、キー値のペアに名前を保持する配列です。私はこれをループしてすべての成分を取り除きたい。私はremoveIngredients関数を呼び出すことでそれを行います。問題は、以下のコードを実行すると、ループは他のすべてのインデックスを取得するだけなので、成分の半分だけが削除されます。

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); 
     } 
     } 
    } 
    }, 

私は1,2,3,4という名前の4つの成分それぞれを作成するときにレシピオブジェクトコード

recipe: { 
    name: '', 
    chef: '', 
    cooktime: '', 
    amount: '', 
    description: '', 
    favorite: false, 
    ingredients: [ 
     {name: ''}, 
    ]} 

にconsole.logを返します。基本的に1と3は正常に渡され、削除されますが、2と4はフォームに戻るときに残ります。

name = name 
i = 0 
this.recipe.ingredients[i][name] 1 

name = name 
i = 1 
this.recipe.ingredients[i][name] 3 
+1

理由だけではなく、 'this.recipes.ingredientsの= []'代わりにあなただけのオブジェクトをリセットするので、それぞれをループの? –

答えて

0

最後のインデックスから0に逆順に反復します。そのようにしてすべてを削除します。あなたが実際には1つを削除する場合も、あなたは内側のループから抜け出す必要があります。

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 
    } 
    } 
} 
+0

それはそれをしました。手伝ってくれてどうもありがとう。 – Mahler7

+0

歓迎:-) – trincot

+0

もう一度やり直してください。 – Mahler7

関連する問題