【发布时间】:2017-06-12 05:31:37
【问题描述】:
我有以下嵌套的 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));
}
});
};
任何帮助将不胜感激
【问题讨论】:
-
看看这个答案stackoverflow.com/a/41175686/1988157会很有帮助
标签: javascript json filter lodash