I have a tree object like below, and I need to search through it. I know there’s already some answers on topics like this here, but they are, unfortunately, do not comply with my structure.
const tree = {
"28": {
"label": "lorem"
"children": {
"188": {
"label": "ipsum"
"children": {
"482": {
"label": "fish"
"children": {
"185": {
"label": "dog"
},
"289": {
"label": "cat"
}
}
}
}
}
}
},
"33": {
"label": "water"
"children": {
"95": {
"label": "fire"
"children": {
"181": {
"label": "gas"
"children": {
"100": {
"label": "station"
}
}
}
"182": {
"label": ""
"children": {
"100": {
"label": "sushi"
}
}
}
}
}
}
}
}
For example, if I’ll search for ‘fish’, output should be like this:
{
"28": {
"label": "lorem"
"children": {
"188": {
"label": "ipsum"
"children": {
"482": {
"label": "fish"
"children": {
"185": {
"label": "dog"
},
"289": {
"label": "cat"
}
}
}
}
}
}
}
}
And if I’ll search for ‘dog’ instead:
{
"28": {
"label": "lorem"
"children": {
"188": {
"label": "ipsum"
"children": {
"482": {
"label": "fish"
"children": {
"185": {
"label": "dog"
}
}
}
}
}
}
}
}
I tried to use these gentlemen’s answers, but couldn’t adapt them to named objects:
How to filter a tree structure while keeping the decendants of the parents that are filtered out?
2
Answers
To search through the tree structure and preserve its hierarchy, you can use a recursive function that:
Here is an example of a solution:
You can replace the searchTerm with ‘dog’ or any other creature you like and it should work.
Use a recursive function that searches in the
children
property recursively.Note that we don’t use here spread syntax and functional approach since it would be slower.