<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let arr = [
{ id: 2, name: "部门B", parentId: 0 },
{ id: 3, name: "部门C", parentId: 1 },
{ id: 1, name: "部门A", parentId: 2 },
{ id: 4, name: "部门D", parentId: 1 },
{ id: 5, name: "部门E", parentId: 2 },
{ id: 6, name: "部门F", parentId: 3 },
{ id: 7, name: "部门G", parentId: 2 },
{ id: 8, name: "部门H", parentId: 4 },
];
const arrToTree = function (arr, pid = 0) {
return arr.reduce((res, cur) => {
if (cur.parentId === pid) {
const children = arrToTree(arr, cur.id);
if (children.length) {
cur.children = children;
}
res.push(cur);
}
return res;
}, []);
};
const tree = arrToTree(arr)
console.log(tree,'tree');
const treeToArr = function(tree){
return tree.reduce((res,cur)=>{
if(!cur.children){
res.push(cur)
}else{
const childrenList = treeToArr(cur.children)
delete cur.children
res.push(cur,...childrenList)
}
return res
},[])
}
const array = treeToArr(tree)
console.log(array,'array');
</script>
</body>
</html>