数据源如:
<!DOCtype html>
<html lang="en-US">
<head>
<title>demo</title>
</head>
<body>
<script>
const json = [
{
"id":4,
"name":"标题1",
"flag":0,
"parentId":1,
"children":[
{
"id":3,
"name":"1-1",
"flag":0,
"parentId":4,
"isLeaf": true,
"children":null
}
]
},
{
"id":5,
"name":"标题2",
"flag":0,
"parentId":1,
"children":[
{
"id":4,
"name":"2-1",
"flag":0,
"parentId":5,
"isLeaf": true,
"children":null
},
{
"id":5,
"name":"2-2",
"flag":0,
"parentId":5,
"checked":true,
"isLeaf": true,
"children":null
}
]
},
{
"id":7,
"name":"标题3",
"flag":0,
"parentId":1,
"children":[
{
"id":6,
"name":"3-1",
"flag":0,
"parentId":7,
"children":[
{
"id": 106,
"name": "3-1-1",
"checked": true,
"isLeaf": true,
"children": null,
}
]
}
]
}
];
function returnSelectedTree(list) {
if (Array.isArray(list) && list.length !== 0) {
list = list.map((item, index) => {
// 哪裏有問題
const children = !item.isLeaf ? item.children.filter(it => it.checked) : [];
if (children.length > 0) {
item = {...item, ...{children: children}};
}
if (!item.isLeaf) {
returnSelectedTree(item.children)
}
return item;
});
return list;
} else {
return false;
}
}
returnSelectedTree(json)
console.log(returnSelectedTree(json));
</script>
</body>
</html>
选中子级别,将其父级输出,如图
选中2-2,输出 标题2的完整树结构,除过2-1;求N层级方法
即:排除未选择项,需要父级完整结构包含选择项。
想通過上面returnSelectedTree方法處理。。。
可根据自己的业务逻辑添加二次查找时的优化逻辑以减少每次查询时预处理节点的逻辑的O(N)的时间复杂度