【发布时间】:2020-02-25 03:42:42
【问题描述】:
我需要根据查询过滤一个看起来像这样的嵌套结构。我需要返回与对象名称中的查询字符串匹配的所有对象,包括子树的父对象。请帮忙,我卡住了。
[
{
name: 'bob',
type: 1,
children: [
{
name: 'bob',
type: 2,
children: [
{
name: 'mike',
type: 3,
children: [
{
name:'bob',
type: 7,
children: []
},
{
name: 'mike',
type: 9,
children: []
}
]
}
]
},
{
name: 'mike',
type: 2
}
]
}
]
现在我能够递归地在树中找到匹配项,但是该函数在第一次匹配时返回对象,并且不会在同一对象的子级别上进行更深入的搜索。有什么建议,我如何修改代码以递归搜索所有级别?
return tree.map(copy).filter(function filterNested(node) {
if (node.name.toLowerCase().indexOf(query) !== -1) {
return true;
}
if (node.children) {
return (node.children = node.children.map(copy).filter(filterNested))
.length;
}
});
如果我正在搜索查询“bob”,预期的结果应该是,
const arr = [
{
name: 'bob',
type: 1,
children: [
{
name: 'bob',
type: 2,
children: [
{
name: 'mike',
type: 3,
children: [
{
name:'bob',
type: 7
},
]
}
]
},
]
}
]
【问题讨论】:
标签: javascript arrays recursion filter