1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| let input = [ { id: 1, val: "学校", parentId: null, }, { id: 2, val: "班级1", parentId: 1, }, { id: 3, val: "班级2", parentId: 1, }, { id: 4, val: "学生1", parentId: 2, }, { id: 5, val: "学生2", parentId: 3, }, { id: 6, val: "学生3", parentId: 3, }, { id: 7, val: "学校2", parentId: null, }, { id: 8, val: "班级1", parentId: 7, }, { id: 9, val: "班级2", parentId: 7, }, { id: 10, val: "学生1", parentId: 8, }, { id: 11, val: "学生2", parentId: 9, }, { id: 12, val: "学生3", parentId: 8, }, ];
function listToTree(arr){ let tree = [] let temp = {} arr.forEach((item) => { item.children = [] temp[item.id] = item if(!item.parentId){ tree.push(item) }else{ temp[item.parentId].children.push(item) } }) return tree } console.log(listToTree(input))
function treeToList(tree){ let list = [] let temp = {} function dfs(children){ for(let node of children){ if(!temp[node.id]){ list.push(node) temp[node.id] = true } dfs(node.children) delete node.children } } dfs(tree) return list } console.log(treeToList(JSON.parse(JSON.stringify(listToTree(input)))))
|