【问题标题】:ES6/JS: Search nested object for string, return trueES6/JS:在嵌套对象中搜索字符串,返回 true
【发布时间】:2020-01-18 13:09:00
【问题描述】:

我有一个要过滤的 vuetify 数据表:https://codepen.io/rasenkantenstein/pen/MWYEvzK。我有一个包含字符串的过滤器,例如“冰”。现在我想检索所有包含一种成分的记录,该成分的名称包含冰。

[
    {

      name: 
      'Frozen Yogurt',
      calories: 159,
      fat: 6.0,
      carbs: 24,
      protein: 4.0,
      ingredients:
        [
          {
            ingName: 'Yogurt',
            ingMeasure: 'gramm',
            ingAmount: 100,
          },
          {
            ingName: 'Ice',
            ingMeasure: 'ml',
            ingAmount: 50,
          }
        ]

    },
    {

      name: 
      'Vanilla Ice Cream',
      calories: 100,
      fat: 2.0,
      carbs: 25,
      protein: 2.0,
      ingredients:
        [
          {
            ingName: 'Milk',
            ingMeasure: 'ml',
            ingAmount: 100,
          },
          {
            ingName: 'Vanilla Sugar',
            ingMeasure: 'g',
            ingAmount: 50,
          },
          {
            ingName: 'Ice',
            ingMeasure: 'g',
            ingAmount: 50,
          }
        ]

    }
  ]

我已经尝试(非常像一个菜鸟)在第 61 行实现过滤器。

filterIng (value) {
  console.log(value)
  if (!this.ingFilterValue) {
      return true;
  }
  value.filter(x => {return x.ingName === this.ingFilterValue})
}

函数 filterIng 已经迭代了每条记录(在控制台中很明显)。 “值”包含一个对象数组,其中一个称为 ingName。

过滤“Ice”时(ingFilterValue = “Ice”),两条记录都应返回 true。在 ingFilterValue = "Yog" 的情况下,只有记录 1 应该返回真,记录 2 应该返回假。

【问题讨论】:

  • 确保两个值的大小写相似。并且还考虑到您当前的比较着眼于整个成分名称......
  • 谢谢。我已经更改了一行以返回 x.ingName.toUpperCase() === this.ingFilterValue.toUpperCase()}。此外,过滤器方法返回一个对象,我需要返回一个布尔值。我认为我在某种程度上使用了错误的方法。

标签: vue.js ecmascript-6 vuetify.js


【解决方案1】:

您可以使用.filter() 函数来完成,首先遍历食谱,然后遍历配料,寻找这样的匹配项

// Assumes allRecipes is your array of recipe objects, 
// and we are looking for "ice"

const regex = /ice/i   // Note the "i" makes it a case-insensitive search

// 你也可以用 regex = new RegExp("ice","i") 来创建它

const recipes = allRecipes.filter( recipe => {
  const ingredients = recipe.ingredients.filter(ing => ing.ingName.match(regex))
  return ingredients.length > 0  // True if any matches
})

//At this point `recipes` will contain the list of filtered recipes

【讨论】:

  • 完美。结果如下: filterIng (value) { if (!this.ingFilterValue) { return true; } const regex = new RegExp(this.ingFilterValue,"i") const ingredients = value.filter(ing => ing.ingName.match(regex)) return ingredients.length > 0
猜你喜欢
  • 2018-08-23
  • 1970-01-01
  • 2021-03-12
  • 2020-06-11
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多