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 结果 = people.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 结果 = people.filter(p => p.animals.some(s => s.species === 'cat'))
这篇关于JS (ES6):基于嵌套数组属性过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!