创建 一个 html 文件即可 打开
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
const list = [
{ id: 1, name: '司令', pid: 0 },
{ id: 2, name: '军长', pid: 1 },
{ id: 3, name: '副军长', pid: 1 },
{ id: 4, name: '旅长', pid: 3 },
{ id: 5, name: '团长', pid: 4 },
]
function arrToTree(list, rootValue) {
let treeData = []
list.forEach(item => {
if (item.pid === rootValue) {
const children = arrToTree(list, item.id)
if (children.length) {
item.children = children
}
treeData.push(item)
}
});
return treeData
}
const treeData = arrToTree(list, 0)
console.log(treeData)
</script>
</head>
<body>
</body>
</html>