Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save xinglongjizi/27bd18177d126656856cc120e8a18b3a to your computer and use it in GitHub Desktop.
Save xinglongjizi/27bd18177d126656856cc120e8a18b3a to your computer and use it in GitHub Desktop.
<script type="text/javascript">
let res = [
{pid: null, id: 1, name: '部门A'},
{pid: null, id: 2, name: '部门B'},
{pid: null, id: 3, name: '部门C'},
{pid: 1, id: 4, name: '部门A'},
{pid: 4, id: 5, name: '部门A'},
{pid: 7, id: 6, name: '部门A'},
{pid: 1, id: 7, name: '部门A'},
{pid: 3, id: 8, name: '部门A'},
{pid: 8, id: 9, name: '部门A'},
];
// 非递归算法,利用的是js中数组和对象存的是数据的指针(引用)
// 组装list为树形结构,hash为工具变量
let list = [];
let hash = {};
// 赋值工具变量hash
for(let i=0; i<res.length; i++){
let tmp = res[i];
hash[tmp.id] = tmp;
}
for(let i=0; i<res.length; i++){
let tmp = res[i];
// 首层
if( tmp.pid === null ){
list.push(tmp);
// 非首层在hash中找父级
}else{
let pNode = hash[tmp.pid];
if( pNode ){
if( !pNode.children ){
pNode.children = []; // 加children属性
}
pNode.children.push(tmp);
}
}
}
console.log(list);
</script>
@abigmiu
Copy link

abigmiu commented Aug 3, 2024

好思路

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment