【问题标题】:Looping Through JavaScript Array of Objects and Removing Values循环遍历 JavaScript 对象数组并删除值
【发布时间】:2017-07-16 17:12:22
【问题描述】:

我正在使用 Vue 和 Rails。下面代码的目标是当用户在添加新配方和返回主页面之间切换时从输入字段中删除文本。这适用于我所有的领域,除了成分。

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

配方对象代码

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

当我创建四个成分时,Console.log 返回,每个成分名为 1,2,3,4。基本上 1 和 3 成功通过并被删除,而当我返回表单时,2 和 4 仍然存在。

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

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

【问题讨论】:

  • 为什么不只是 this.recipes.ingredients = [] 而不是循环遍历每个,因为您只想重置对象?

标签: javascript arrays loops object vue.js


【解决方案1】:

向后遍历数组,因此从最后一个索引到 0。这样您就可以将它们全部删除。另外,当你实际删除一个时,你应该跳出内部循环:

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

【讨论】:

  • 做到了。非常感谢您的帮助。
猜你喜欢
  • 2019-11-10
  • 2015-10-15
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
  • 2019-12-16
  • 1970-01-01
相关资源
最近更新 更多