【发布时间】:2019-09-12 18:54:37
【问题描述】:
我想通过属性 'name' 的值搜索嵌套对象,结果将保留其所有父对象。
例如,
const object = [
{
name: 'Mary',
children: [
{
name: 'Jack',
},
{
name: 'Kevin',
children: [
{
name: 'Lisa',
}
]
}
]
},
{
name: 'Gina',
children: [
{
name: 'Jack',
}
]
}
]
如果我搜索“玛丽”,它应该是返回:
[
{
name: 'Mary',
}
]
如果我搜索“Jack”,它应该是返回:
[
{
name: 'Mary',
children: [
{
name: 'Jack',
}
]
},
{
name: 'Gina',
children: [
{
name: 'Jack',
}
]
}
]
如果我搜索“Lisa”,它应该是返回:
[
{
name: 'Mary',
children: [
{
name: 'Jack',
children: [
{
name: 'Lisa',
}
]
}
]
}
]
我尝试了一些方法,但我只能过滤两层。如下:
return object.filter(data => {
if (data.children) {
return data.name.includes(keyword) || data.children.find(item => item.name.includes(keyword));
}
return data.name.includes(keyword);
})
有人能指出我正确的方向吗?谢谢!
【问题讨论】:
-
深度优先搜索算法?
-
同一血统中有多个同名的人怎么办?例如,在 Lisa 的案例中,如果将“Mary”替换为“Lisa”会怎样?
-
@JonathanHamel 感谢您指出它被称为深度优先搜索!我学到了很多。
-
@kingkupps 我也很好奇。在您的示例中,这些解决方案将失败。
标签: javascript object filter nested