I am having a tree structured data which should be filtered and the result should retain the tree structure:
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"
}
];
I want to filter the tree. I am using this method:
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;
}
});
}
It is working perfectly fine. This question has been previously asked on this Stack Overflow link.
Although, I have one use case that if the grandchild
(only in case of type grandchild
and not in child
or parent
) text is matched then the siblings node should also be returned along with their respective parent node. Answer may be simple, but somehow I am not able to think how to do that.
So if I pass this: Grandchild 2
,
the expected output should be:
[
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
type: "Child",
nodes: [
{
text: "Grandchild 1"
type: "Grandchild"
},
{
text: "Grandchild 2"
type: "Grandchild"
}
]
}
]
}
]