ES6 / JS:在嵌套对象中搜索字符串,返回true

问题描述 投票:0回答:1

我有一个要过滤的可视化数据表: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应该返回true,而记录2应该返回false。

vue.js ecmascript-6 vuetify.js
1个回答
0
投票

您可以使用.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
© www.soinside.com 2019 - 2024. All rights reserved.