【发布时间】:2021-06-29 00:56:14
【问题描述】:
我有一个应该过滤的树结构数据,结果应该保留树结构:
var tree = [
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
type: "Child",
nodes: [
{
text: "Grandchild 1"
type: "Grandchild"
},
{
text: "Grandchild 2"
type: "Grandchild"
}
]
},
{
text: "Child 2",
type: "Child"
}
]
},
{
text: "Parent 2",
type: "Parent"
},
{
text: "Parent 3",
type: "Parent"
}
];
我想过滤树。我正在使用这种方法:
function filter(array, text) {
return array.filter(function iter(o) {
var temp;
if (o.text === text) {
return true;
}
if (!Array.isArray(o.nodes)) {
return false;
}
temp = o.nodes.filter(iter);
if (temp.length) {
o.nodes = temp;
return true;
}
});
}
它工作得很好。这个问题之前已经在Stack Overflow link 上提出过。
虽然,我有一个用例,如果 grandchild(仅在 grandchild 类型的情况下,而不是在 child 或 parent 中)文本匹配,那么兄弟节点也应该与它们一起返回各自的父节点。答案可能很简单,但不知怎的,我想不出该怎么做。
所以如果我通过这个:Grandchild 2,
预期的输出应该是:
[
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
type: "Child",
nodes: [
{
text: "Grandchild 1"
type: "Grandchild"
},
{
text: "Grandchild 2"
type: "Grandchild"
}
]
}
]
}
]
【问题讨论】:
标签: javascript