返回父对象和子对象的javascript对象上的动态查询搜索/筛选
在我的应用程序中,我有一个嵌套对象(基本对象,不使用SQL),它由父对象和子对象组成,呈现为如下轮廓:返回父对象和子对象的javascript对象上的动态查询搜索/筛选,javascript,nested,Javascript,Nested,在我的应用程序中,我有一个嵌套对象(基本对象,不使用SQL),它由父对象和子对象组成,呈现为如下轮廓: - item 1 ⁃ Child 1 ⁃ Grand 1 (date = May 21) ⁃ Grand 2 ⁃ More children 1 ⁃ More children 2 ⁃ [could be infinitely deep] ⁃
- 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]
{
Name: “item 1”,
Date: June 3 2017,
Children: [ …children]
}
- item 1
⁃ Child 1
⁃ **Grand 2**
⁃ More children 1
⁃ More children 2
⁃ [could be infinitely deep]
每个对象都具有如下属性:
- 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]
{
Name: “item 1”,
Date: June 3 2017,
Children: [ …children]
}
- item 1
⁃ Child 1
⁃ **Grand 2**
⁃ More children 1
⁃ More children 2
⁃ [could be infinitely deep]
我有一个搜索框,用户可以在其中输入一个词,并返回任何匹配的对象,加上它的父对象和子对象。例如,如果有人搜索“Grand 2”,它将如下所示:
- 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]
{
Name: “item 1”,
Date: June 3 2017,
Children: [ …children]
}
- item 1
⁃ Child 1
⁃ **Grand 2**
⁃ More children 1
⁃ More children 2
⁃ [could be infinitely deep]
以下是我用于过滤的代码,它运行良好:
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);
}
});
};
我正在苦苦挣扎的是如何组合搜索,比如“Grand 2或date=2017年5月21日”。这将返回这个
• item 1
⁃ Child 1
⁃ Grand 1 (date = May 21)
⁃ Grand 2
⁃ More children 1
⁃ More children 2
⁃ [could be infinitely deep]
我建议通过接受一个函数并调用它来参数化过滤器逻辑,而不是测试字符串:
if(\u.includes(\u.toLower(item.name),\u.toLower(filter))
将变成if(filter(item))
我从这个问题中删除了react&redux标记,因为这个问题在任何javascript环境中都是有效的。