如何有效地过滤保留其现有结构的树形视图? [英] How to effectively filter tree view retaining its existing structure?
问题描述
我有一个树状的JSON,应该对其进行过滤,并且结果应保留该树状结构.
I am having a tree structured JSON which should be filtered and the result should retain the tree structure.
var tree = [
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
type: "Child",
nodes: [
{
text: "Grandchild 1"
type: "Grandchild"
},
{
text: "Grandchild 2"
type: "Grandchild"
}
]
},
{
text: "Child 2",
type: "Child"
}
]
},
{
text: "Parent 2",
type: "Parent"
},
{
text: "Parent 3",
type: "Parent"
}
];
示例:
1)如果搜索查询为父级1"
1)If search query is Parent 1
预期结果:
[
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
type: "Child",
nodes: [
{
text: "Grandchild 1"
type: "Grandchild"
},
{
text: "Grandchild 2"
type: "Grandchild"
}
]
},
{
text: "Child 2",
type: "Child"
}
]
}
]
2)如果搜索查询为孩子1"
2)If search query is Child 1
预期结果:
[
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
type: "Child",
nodes: [
{
text: "Grandchild 1"
type: "Grandchild"
},
{
text: "Grandchild 2"
type: "Grandchild"
}
]
}
]
}
]
3)如果搜索查询是孙子2",则
3)If search query is Grandchild 2
预期结果:
[
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
type: "Child",
nodes: [
{
text: "Grandchild 2"
type: "Grandchild"
}
]
}
]
}
]
我需要基于节点级别(此处为 type )保留树结构.到目前为止,我已经尝试过递归过滤,但是无法重新映射结果.
I need to retain the tree structure based on the node level (type here). So far I have tried filtering recursively but couldn't re-map the results.
angular.module("myApp",[])
.filter("filterTree",function(){
return function(items,id){
var filtered = [];
var recursiveFilter = function(items,id){
angular.forEach(items,function(item){
if(item.text.toLowerCase().indexOf(id)!=-1){
filtered.push(item);
}
if(angular.isArray(item.items) && item.items.length > 0){
recursiveFilter(item.items,id);
}
});
};
recursiveFilter(items,id);
return filtered;
};
});
});
我的JSON非常大,因此基于类型的重新映射应在过滤器本身中完成. 请指教.
My JSON is pretty large and hence remapping based on types are expected to be done in the filter itself. Please advice.
推荐答案
您可以使用嵌套的递归方法并过滤树,同时尊重找到的项.
You could use a nested recursive approach and filter the tree, while respecting the found item.
此解决方案不会变异原始数据.
function filter(array, text) {
const getNodes = (result, object) => {
if (object.text === text) {
result.push(object);
return result;
}
if (Array.isArray(object.nodes)) {
const nodes = object.nodes.reduce(getNodes, []);
if (nodes.length) result.push({ ...object, nodes });
}
return result;
};
return array.reduce(getNodes, []);
}
var tree = [{ text: "Parent 1", nodes: [{ text: "Child 1", type: "Child", nodes: [{ text: "Grandchild 1", type: "Grandchild" }, { text: "Grandchild 2", type: "Grandchild" }] }, { text: "Child 2", type: "Child" }] }, { text: "Parent 2", type: "Parent" }, { text: "Parent 3", type: "Parent" }];
console.log(filter(tree, 'Parent 1'));
console.log(filter(tree, 'Child 1'));
console.log(filter(tree, 'Grandchild 2'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于如何有效地过滤保留其现有结构的树形视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!