JS(ES6):根据嵌套数组属性过滤数组 [英] JS (ES6): Filter array based on nested array attributes
问题描述
我有一个数组,看起来像这样:
I have an array, which looks like this:
const persons = [
{
name: "Joe",
animals: [
{species: "dog", name: "Bolt"},
{species: "cat", name: "Billy"},
]
},
{
name: "Bob",
animals: [
{species: "dog", name: "Snoopy"}
]
}
];
现在我要根据物种进行过滤. 例如:每个有猫的人都应返回:
Now I want to filter based on the species. For example: every person which has a cat, should be returned:
const result = [
{
name: "Joe",
animals: [
{species: "dog", name: "Bolt"},
{species: "cat", name: "Billy"},
]
}
];
我已经尝试过使用filter()
方法,如下所示:
I have tried with the the filter()
method like this:
const result = persons.filter(p => p.animals.filter(s => s.species === 'cat'))
但这不会返回期望的结果(返回两个人).
But this doesn't return the desired result (it returns both persons).
如何基于嵌套数组的属性过滤数组?
How can I filter the array bases on an attribute of a nested array?
推荐答案
您的内部过滤器仍然为狗狗返回真实"值(空数组).添加.length
,以使任何结果都不会成为0
("falsey")
Your inner filter still returns a "truthy" value (empty array) for the dog person. Add .length
so that no results becomes 0
("falsey")
const result = persons.filter(p => p.animals.filter(s => s.species === 'cat').length)
对于每个注释和其他几个答案,由于目标是从内部循环中获取真实值,因此.some
会更好地完成工作,因为如果有的话直接返回true项目匹配.
Per comments and several other answers, since the goal is to get a truthy value from the inner loop, .some
would get the job done even better because it directly returns true if any items match.
const result = persons.filter(p => p.animals.some(s => s.species === 'cat'))
这篇关于JS(ES6):根据嵌套数组属性过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!