问答题61/125数组转树

将下列数组进行转换:

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 创建

赞赏支持

预览

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