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
| let list = [ { id: 1, name: '部门A', parentId: 0 }, { id: 2, name: '部门B', parentId: 0 }, { id: 3, name: '部门C', parentId: 1 }, { id: 4, name: '部门D', parentId: 1 }, { id: 5, name: '部门E', parentId: 2 }, { id: 6, name: '部门F', parentId: 3 }, { id: 7, name: '部门G', parentId: 2 }, { id: 8, name: '部门H', parentId: 4 }, ] function convert(list) { const res = [] const map = {} list.forEach(item => map[item.id] = item) list.forEach(item => { if (item.parentId === 0) return res.push(item) const parent = map[item.parentId] if (parent.children) { parent.children.push(item) } else { parent.children = [item] } }) return res }
let result = convert(list) result = [{ id: 1, name: '部门A', parentId: 0, children: [{ id: 3, name: '部门3', parentId: 1, children: [{ id: 6, name: '部门6', parentId: 3, }] }] }, ]
|