1👍
You can traverse the tree by a recursive function. You can think of the data structure as an M tree. Also I have used the closures for data encapsulation.
const data = [
{
Name: 'Name Level 1',
Title: 'Apple',
children: [
{
Name: 'Name Level 2',
Title: 'Title Level 2',
children: [{
Name: 'Name Level 3',
Title: 'Application',
children: null
}]
}
]
},
{
Name: 'Name Level 1',
Title: 'Apple',
children: null
}
]
const filter = (item, search, textKey) => {
let result = []
const _filter = (item, search, textKey) => {
for (const leaf of item) {
if (leaf[textKey].indexOf(search) !== -1) {
result = [...result, {Name: leaf.Name, Title: leaf.Title}]
}
leaf.children ? _filter(leaf.children, search, textKey) : null
}
}
_filter(item, search, textKey)
return result
}
console.log(filter(data, 'App', 'Title'))
Source:stackexchange.com