<!DOCTYPE html>
<html ng-app="my_app">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
// 列表结合
let list = [
{id : 1, name : "浙江", upperid : null},
{id : 2, name : "江苏", upperid : null},
{id : 3, name : "福建", upperid : null},
{id : 11, name : "杭州", upperid : 1},
{id : 12, name : "嘉兴", upperid : 1},
{id : 21, name : "苏州", upperid : 2 },
{id : 22, name : "无锡", upperid : 2},
{id : 31, name : "福州", upperid : 3},
{id : 32, name : "厦门", upperid : 3},
{id : 111, name : "萧山", upperid : 11},
{id : 112, name : "临安", upperid : 11},
{id : 121, name : "嘉善", upperid : 12 },
{id : 122, name : "桐乡", upperid : 12 },
{id : 211, name : "吴江", upperid : 21},
{id : 212, name : "常熟", upperid : 21},
];
// 递归放方法,将列表转化成树
function getTree() {
let tree = [];
// 获取根节点
let rootNodes = list.filter(a => a.upperid == null);
rootNodes.forEach((rootNode, i) => {
// 获取根节点路径
rootNode.path = [];
rootNode.path.push(rootNode.id);
GetChildren(rootNode, list);
tree.push(rootNode);
});
// 递归获取子节点
function GetChildren(upperNode, list) {
let childNodes = list.filter(a => a.upperid == upperNode.id);
upperNode.children = null;
if (childNodes != null && childNodes.length > 0) {
childNodes.forEach((childNode, i) => {
// 获取子节点路径
childNode.path = [];
childNode.path = childNode.path.concat(upperNode.path);
childNode.path.push(childNode.id);
GetChildren(childNode, list);
});
upperNode.children = childNodes;
}
}
return tree;
}
// 根据节点,将节点和祖先节点设置为true(这里不用path属性)
function setSelectedNode(tree, ids) {
tree.forEach((item, i) => {
let selected = false;
if (ids.indexOf(item.id) != -1) {
selected = true;
}
if (item.children) {
setSelectedNode(item.children, ids);
if (selected == false) {
let selectedChildren = item.children.filter(a => a.selected == true);
if (selectedChildren.length > 0) {
selected = true;
}
}
}
item.selected = selected;
});
return tree;
}
// 调用方法,将列表转化成树
let tree = getTree();
console.log(JSON.stringify(tree));
// 根据将节点(福建,苏州,嘉善)和祖先节点设置为true(这里不用path属性)
tree = setSelectedNode(tree, [3, 21, 121]);
console.log(JSON.stringify(tree));
</script>
</head>
<body>
</body>
</html>
js 递归
于 2022-09-14 21:33:43 首次发布