Answer the question
In order to leave comments, you need to log in
How to filter tree arrays?
Hello everyone, I have the following item.
{
id: 1,
name: "Москва",
children: [
{
id:2,
name: 'Академический'
children: [
{
id:3,
name: 'ул. Янгеля'
}
....
]
}
....
]
}
Answer the question
In order to leave comments, you need to log in
The filter function receives an array and a search string, and is called recursively on the child elements of each of the elements of the passed array. Returns elements whose name contains the search string or whose child elements are left after the recursive call.
const filter = (arr, str) => (arr || [])
.map(n => ({ ...n, children: filter(n.children, str) }))
.filter(n => n.name.includes(str) || n.children.length);
computed: {
filteredItems() {
return filter(this.items, this.search);
},
},
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question