[英]How to create a nested filter with lodash
我有以下嵌套的JSON数据结构。 每个节点可以具有任意数量的子代,数据可以是任意数量的深度节点。
[{
id : "a",
path : "a"
}, {
id : "b",
path : "b"
}, {
id : "c",
path : "c",
children: [{
id : "a",
path : "c/a"
}, {
id : "b",
path : "c/b",
children: [{
id : "a",
path : "c/b/a"
}, {
id : "b",
path : "c/b/b"
}]
}]
}]
我需要在lodash(v3.10.1)中创建一个函数,该函数返回匹配路径和任何父对象的嵌套JSON对象。 例如,如果我要搜索“ b”,则过滤器应返回以下内容:
[{
id : "b",
path : "b"
}, {
id : "c",
path : "c",
children: [{
id : "b",
path : "c/b",
children: [{
id : "a",
path : "c/b/a"
}, {
id : "b",
path : "c/b/b"
}]
}]
}]
我最初的尝试是这样的,但确实奏效了:
const filterTree = (filter, list) => {
return _.filter(list, (item) => {
if (item.path) {
return _.includes(item.path.toLowerCase(), filter.toLowerCase());
} else if (item.children) {
return !_.isEmpty(filterTree(filter, item.children));
}
});
};
任何帮助将非常感激
第一个问题是, if (item.path)
始终为true
,则递归调用永远不会发生。
为了获得所需的结果,在递归情况下进行过滤后,必须更新item.children
,因为_.filter
不会使传递给它的数组发生突变。 如果您不想更改输入, _.cloneDeep
使用_.cloneDeep
进行复制。
const data = [{"id":"a","path":"a"},{"id":"b","path":"b"},{"id":"c","path":"c","children":[{"id":"a","path":"c/a"},{"id":"b","path":"c/b","children":[{"id":"a","path":"c/b/a"},{"id":"b","path":"c/b/b"}]}]}]; const filterTree = (filter, list) => { return _.filter(list, (item) => { if (_.includes(_.toLower(item.path), _.toLower(filter))) { return true; } else if (item.children) { item.children = filterTree(filter, item.children); return !_.isEmpty(item.children); } }); }; console.log(filterTree('b', data));
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.