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
No one has answered this question yet
Check out similar questions: