gpt4 book ai didi

javascript - 过滤对象javascript中的数组

转载 作者:行者123 更新时间:2023-11-29 20:56:46 25 4
gpt4 key购买 nike

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

我有这个 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 也是一个数组,因此您也需要遍历 ingredients 数组。

正如所写,只有当成分等于:

    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' ) ) )
)

关于javascript - 过滤对象javascript中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48945891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com