Created
September 3, 2021 03:58
-
-
Save xinglongjizi/27bd18177d126656856cc120e8a18b3a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
好思路