[英]How to recursively filter tree JSON in React/Javascript?
我需要过滤此 JSON 树数据以实现搜索(过滤树)功能。 结构如下所示:
Array filter > map 只会进入第一级。 我如何遍历到子级的最后一级(过滤器应该在客户之后的所有级别上工作)并使用字符串进行相应的过滤(包括逻辑)
{
"path":"Customers",
"sha":"Customers",
"lazy":false,
"type":"tree",
"tree":[
{
"path":"Bob Rivers",
"type":"tree",
"sha":"Bob Rivers",
"lazy":false,
"tree":[
{
"path":"Services",
"type":"tree",
"sha":"Services",
"lazy":true,
"url":"http://localhost:3000/services",
"tree":[
{
"path":"Service_X",
"type":"tree",
"sha":"Service_X",
"lazy":true,
"url":"http://localhost:3000/Service_X",
"tree":[
{
"lazy":true,
"path":"Service_X_child",
"mode":"040000",
"type":"tree",
"sha":"Service_X_child",
"url":"http://localhost:3000/Service_X_child",
"tree":[
{
"lazy":true,
"path":"ABC",
"mode":"040000",
"type":"blob",
"sha":"ABC",
"url":""
},
{
"lazy":true,
"path":"DEF",
"mode":"040000",
"type":"blob",
"sha":"DEF",
"url":""
}
]
},
{
"lazy":true,
"path":"Service_X_child_2",
"mode":"040000",
"type":"tree",
"sha":"Service_X_child_2",
"url":"http://localhost:3000/Service_X_child_2"
}
]
},
{
"path":"Service_Y",
"type":"tree",
"sha":"Service_Y",
"lazy":true,
"url":"http://localhost:3000/Service_Y"
}
],
}
],
}
],
}
示例输入是如果搜索过滤器 = "DEF"(路径将被检查),数据将减少到这个
{
"path":"Customers",
"sha":"Customers",
"lazy":false,
"type":"tree",
"tree":[
{
"path":"Bob Rivers",
"type":"tree",
"sha":"Bob Rivers",
"lazy":false,
"tree":[
{
"path":"Services",
"type":"tree",
"sha":"Services",
"lazy":true,
"url":"http://localhost:3000/services",
"tree":[
{
"path":"Service_X",
"type":"tree",
"sha":"Service_X",
"lazy":true,
"url":"http://localhost:3000/Service_X",
"tree":[
{
"lazy":true,
"path":"Service_X_child",
"mode":"040000",
"type":"tree",
"sha":"Service_X_child",
"url":"http://localhost:3000/Service_X_child",
"tree":[
{
"lazy":true,
"path":"DEF",
"mode":"040000",
"type":"blob",
"sha":"DEF",
"url":""
}
]
}
]
}
],
}
],
}
],
}
我尝试了以下解决方案但没有奏效: 递归过滤搜索栏的 json 数据
这个人明确提到将 JSON 树数据扁平化到数组并没有解决他的问题
https://www.geeksforgeeks.org/how-to-filter-object-array-based-on-attributes/
const TreeNode = ({node , searchString}) => {
if(!node.tree){
return node.path.toLowerCase().includes(searchString.toLowerCase())? node:null
}
node.tree = node.tree.map(childNode => TreeNode(
{
node:childNode, searchString
}
)).filter(n => n);
return node.tree.length? node:null;
}
这个递归 function 解决了我的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.