过滤对象javascript中的数组

过滤对象javascript中的数组,javascript,filter,Javascript,Filter,也许是星期五早上,我有点时间,但不明白为什么这不起作用 我有这个JSON var recipes = [{ name: "Beef Lasagne", ingredients: [ "mince", "pasta", "sauce", "tomatoes" ]}] 我可以这样做:recipes.f

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

我有这个JSON

var recipes = [{
            name: "Beef Lasagne",
            ingredients: [
                "mince",
                "pasta",
                "sauce",
                "tomatoes"
            ]}]
我可以这样做:
recipes.filter(recipe=>recipe.name.includes('e'))
并且它可以正确过滤

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

我知道我正在尝试在ex1中过滤一个字符串,然后在ex2中过滤一个数组,我还需要做什么才能使第二个数组中的过滤器正常工作?

您可以使用数组上的
.join(“”
将其转换为字符串,并能够使用
。includes()
您最初想要的方式:

var配方=[
{
名称:“牛肉千层面”,
成分:[
“切碎”,
“意大利面”,
“酱汁”,
“西红柿”
]
},
{
名称:“生面食”,
成分:[
“意大利面”
]
}
];
recipes=recipes.filter(recipe=>recipe.Components.join(“”)。包括('e');
console.log(配方)
数组。includes()
将查找特定元素。由于配料也是一个数组,因此也需要在配料数组上循环

如前所述,只有当成分等于:

    ingredients: [
        "mince",
        "pasta",
        "sauce",
        "tomatoes",
        "e"
    ]
因此,您可能需要以下内容:

recipes.filter( recipe => recipe.ingredients.some( ingredient => ingredient.includes( 'e' ) ) );
var配方=[{
名称:“牛肉千层面”,
成分:[
“切碎”,
“意大利面”,
“酱汁”,
“西红柿”
]
},
{
名称:“不含e的牛肉千层面”,
成分:[
“minc”,
“过去”,
“番茄”
]
},
{
名称:“无肉馅酱牛肉千层面”,
成分:[
“酱汁”,
“意大利面”,
“西红柿”
]
}
]
console.log(
recipes.filter(recipe=>recipe.components.some(component=>component.includes('e'))
)
console.log(
recipes.filter(recipe=>recipe.components.some(component=>component.startsWith('min'))
)
试试这个:

recipes.filter(recipe => recipe.ingredients.filter(ingredient => ingredient.includes('e')).length > 0)

你不能像那样过滤一个数组
recipe.components.includes('e')
-你也需要向该数组添加一个过滤器,或者添加一个仅仅是“e”
String的成分。includes()
将在另一个字符串中查找特定的字符串
Array.includes()
将查找精确的元素。因此
recipe.components.includes('e')
仅当字符串
'e'
是配料的一部分时才有效。你是不是想搜索其中是否有含有字母“e”的成分?@Shilly是的exactly@Shilly您应该将该评论转换为答案。您的预期输出是什么?是的,我想这是可行的,但是如果您想更改我的筛选器,以便我可以改为说
startsWith()
。因此,只返回我的配方,其中的成分开始….@thewalrus你的意思是成分必须以“e”开头吗?全部还是部分?是的,这就是我想要的!这允许我更改字符串方法,即从
includes
更改为
startsWith
。谢谢您可以通过这种方式使用任何数组方法来映射/过滤/减少特定字段。如果您使用像lodash或下划线这样的库,它们也会有这些库的内置版本。当然。我喜欢这种方法,因为它是可扩展的。是的,我以前用过下划线,但学习时尽量远离图书馆:)