过滤对象javascript中的数组

海象

也许是星期五早上,我有一点时间,但看不到为什么这不起作用。

我有这个JSON

var recipes = [{
            name: "Beef Lasagne",
            ingredients: [
                "mince",
                "pasta",
                "sauce",
                "tomatoes"
            ]}]

我可以这样做:recipes.filter(recipe => recipe.name.includes('e'))它可以正确过滤

但是,当我尝试这样做时: recipes.filter(recipe => recipe.ingredients.includes('e'))

我得到我试图在ex1中过滤字符串,然后在ex2中对数组进行即时过滤,我还需要做些什么才能使第二个过滤器正常工作?

雪莉

Array.includes()将寻找一个特定的元素。由于成分也是数组,因此您也需要遍历成分数组。

因此,按照书面规定,只有在成分相等的情况下它才有效:

    ingredients: [
        "mince",
        "pasta",
        "sauce",
        "tomatoes",
        "e"
    ]

因此,您可能想要类似:

recipes.filter( recipe => recipe.ingredients.some( ingredient => ingredient.includes( 'e' ) ) );

var recipes = [{
    name: "Beef Lasagne",
    ingredients: [
      "mince",
      "pasta",
      "sauce",
      "tomatoes"
    ]
  },
  {
    name: "Beef Lasagne without e",
    ingredients: [
      "minc",
      "past",
      "tomatos"
    ]
  },
  {
    name: "Beef Lasagne with sauce and no mince",
    ingredients: [
      "sauce",
      "pasta",
      "tomatoes"
    ]
  }
]

console.log(
    recipes.filter( recipe => recipe.ingredients.some( ingredient => ingredient.includes( 'e' ) ) )
)
console.log(
    recipes.filter( recipe => recipe.ingredients.some( ingredient => ingredient.startsWith( 'min' ) ) )
)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章