D
D
Denis Labutin2021-02-18 09:34:23
JavaScript
Denis Labutin, 2021-02-18 09:34:23

How to filter tree arrays?

Hello everyone, I have the following item.

{
id: 1,
name: "Москва",
children: [
    {
        id:2,
        name: 'Академический'
        children: [
                {
                        id:3,
                        name: 'ул. Янгеля'
                }
               ....
        ]
    }
....
]
}

That is, there are 3 levels of nesting, the same parent.
I need to do a character search somehow, i.e. the match can be in the name of the district, and in the name of the street. And you need to leave the entire branch if a match is found in the street. Those. City -> district -> street

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-02-18
@lazy_den

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);

With respect to vue - format the filtered array as a computed property:
computed: {
  filteredItems() {
    return filter(this.items, this.search);
  },
},

https://jsfiddle.net/pL2fh506/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question