Dynamic search / query filter on javascript object returning parent and child elements

In my application, I have a nested object (a basic non-SQL object) that is made up of parents and children that appear as an outline like this:

-  item 1
    ⁃   Child 1
        ⁃   Grand 1 (date = May 21)
        ⁃   Grand 2
            ⁃   More children 1
            ⁃   More children 2
               ⁃    [could be infinitely deep]
    ⁃   Child 2
        ⁃   grandchild1
        ⁃   Grandchild 2
            ⁃   [could be infinitely deep]

      

Each object has the following properties:

{
    Name: "item 1",
    Date: June 3 2017,
    Children: [ …children]
}

      

I have a search box where a user can enter a term and that returns any matching object as well as its parents and children. For example, someone is looking for "Grand 2", it will look like this:

-   item 1
    ⁃   Child 1
        ⁃   **Grand 2**
            ⁃   More children 1
            ⁃   More children 2
                ⁃   [could be infinitely deep]

      

Here is the code I am using for filtering and it works well:

export const filterTree = (filter, list) => {
    return _.filter(list, (item) => {
        if (_.includes(_.toLower(item.name), _.toLower(filter))) {
          item.collapsed = false;
            return true;
        } else if (item.children) {
          item.collapsed = false;
            item.children = filterTree(filter, item.children);
            return !_.isEmpty(item.children);
        }
    });
};

      

What I'm struggling with is consolidating queries like "Grand 2 OR date = May 21, 2017". To bring it back.

β€’   item 1
    ⁃   Child 1
        ⁃   Grand 1 (date = May 21)
        ⁃   Grand 2
            ⁃   More children 1
            ⁃   More children 2
                ⁃   [could be infinitely deep]

      

+3


source to share





All Articles