API: 数组+初始 pid(一般为 0) 实现思路:用递归或者轮询数组一步步创建一个新的数组对象 要求拍平的原数据如下: 1 2 3 4 5 6 7 let arr = [ { id: 1, name: '部门1', pid: 0 }, { id: 2, name: '部门2', pid: 1 }, { id: 3, name: '部门3', pid: 1 }, { id: 4, name: '部门4', pid: 3 }, { id: 5, name: '部门5', pid: 4 }, ] 期望得到的数据格式: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ;[ { id: 1, name: '部门1', pid: 0, children: [ { id: 2, name: '部门2', pid: 1, children: [], }, { id: 3, name: '部门3', pid: 1, children: [ // 结果 ,,, ], }, ], }, ] 版本 1 反手就是一个递归 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 function getChild(data, result, pid) { for (let item of data) { if (item.pid === pid) { const newItem = { ...item, child: [] } result.push(newItem) getChild(data, result, item.id) } } } function arrayToTree(data, pid) { const result = [] getChild(data, result, pid) return result } arrayToTree(arr, 0) 版本 1.2 最简递归 1 2 3 4 5 6 7 8 9 10 11 12 function arrayToTree(data = [], pid = 0) { let tempData = [] if (data && data.length) { for (let item of data) { if (item.pid === pid) { item.child = arrayToTree(data, item.id) tempData.push(item) } } } return tempData } 版本 2 老子会 Map 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 function arrayToTree(arr) { const result = [] const itemMap = {} // arr数据专为key为item.id的map for (const item of arr) { itemMap[item.id] = { ...item, child: [] } } for (const item of arr) { const id = item.id const pid = item.pid const treeItem = itemMap[id] if (pid === 0) { result.push(treeItem) } else { if (!itemMap[pid]) { itemMap[pid] = { child: [], } } itemMap[pid].child.push(treeItem) } } return result } 版本 3 map 终极学以致用 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 function arrayToTree(items) { const result = [] const itemMap = {} for (const item of items) { const id = item.id const pid = item.pid if (!itemMap[id]) { itemMap[id] = { children: [], } } itemMap[id] = { ...item, child: itemMap[id]['children'], } const treeItem = itemMap[id] if (pid === 0) { result.push(treeItem) } else { if (!itemMap[pid]) { itemMap[pid] = { children: [], } } itemMap[pid].children.push(treeItem) } } return result }