问答题1158/1588数组转树

将下列数组进行转换:

1const list = [ 2 {id: 1, name: '部门1', pid: 0}, 3 {id: 2, name: '部门1-1', pid: 1}, 4 {id: 3, name: '部门1-2', pid: 1}, 5 {id: 4, name: '部门1-1-1', pid: 2}, 6 {id: 5, name: '部门1-2-1', pid: 3}, 7 {id: 6, name: '部门2', pid: 0}, 8 {id: 7, name: '部门2-1', pid: 6}, 9 {id: 8, name: '部门3', pid: 0}, 10]

期望结果:

1const listTree = [ 2 { 3 id: 1, 4 name: '部门1', 5 pid: 0, 6 children: [ 7 { 8 id: 2, 9 name: '部门1-1', 10 pid: 1, 11 children: [ 12 { 13 id: 4, 14 name: '部门1-1-1', 15 pid: 2, 16 children: [] 17 } 18 ] 19 }, 20 { 21 id: 3, 22 name: '部门1-2', 23 pid: 1, 24 children: [ 25 { 26 id: 5, 27 name: '部门1-2-1', 28 pid: 3, 29 children: [] 30 } 31 ] 32 } 33 ] 34 }, 35 { 36 id: 6, 37 name: '部门2', 38 pid: 0, 39 children: [ 40 { 41 id: 7, 42 name: '部门2-1', 43 pid: 6, 44 children: [] 45 } 46 ] 47 }, 48 { 49 id: 8, 50 name: '部门3', 51 pid: 0, 52 children: [] 53 } 54] 55
难度:
2023-05-15 创建

参考答案:

递归实现

1// 递归查找获取子节点 2const getChild = (list, result, pid) => { 3 for(const item of list) { 4 if(item.pid === pid) { 5 const newItem = { ...item, children: [] }; 6 result.push(newItem); 7 getChild(list, newItem.children, item.id); 8 } 9 } 10} 11// 调用递归实现 12const listToTree = (list, pid) => { 13 const result = []; 14 getChild(list, result, pid); 15 return result; 16} 17listToTree(list, 0)

Map对象实现

1const listToTree = (list) => { 2 // 最终树形结构输出的结果 3 const result = []; 4 const itemMap = {}; 5 for(const item of list) { 6 const id = item.id; 7 const pid = item.pid; 8 if(!itemMap[id]) { 9 itemMap[id] = { 10 children: [], 11 }; 12 } 13 itemMap[id] = { 14 ...item, 15 children: itemMap[id]["children"], 16 }; 17 const treeItem = itemMap[id]; 18 if(pid === 0) { 19 result.push(treeItem) 20 } else { 21 if(!itemMap[pid]) { 22 itemMap[pid] = { 23 children: [] 24 } 25 } 26 itemMap[pid].children.push(treeItem); 27 } 28 } 29 return result; 30} 31 32listToTree(list, 0)

filter实现

1const listToTree = (list, key) => { 2 const tree = list.filter(function(parent) { 3 // 返回每一项得的子级数据 4 const branchArr = list.filter((child) => parent.id === child[key]); 5 parent.children = []; 6 // 如果存在子级,则给父级添加一个children属性并赋值 7 if (branchArr.length > 0) { 8 parent.children = branchArr; 9 } 10 // 返回第一层 11 return parent[key] == 0; 12 }); 13 return tree; 14} 15// 传入原始数据和父级pid的key 16listToTree(list, 'pid')

最近更新时间:2023-08-20

赞赏支持

预览

题库维护不易,您的支持就是我们最大的动力!