[ { id: 1, text: '节点1', parentId: 0 //这里用0表示为顶级节点 }, { id: 2, text: '节点1_1', parentId: 1 //通过这个字段来确定子父级 } ... ] 转成 [ { id: 1, text: '节点1', parentId: 0, children: [ { id:2, text: '节点1_1', parentId:1 } ] } ] // 1 function listToTree(data) { let temp = {}; let treeData = []; for (let i = 0; i < data.length; i++) { temp[data[i].id] = data[i]; } for (let i in temp) { if (+temp[i].parentId != 0) { if (!temp[temp[i].parentId].children) { temp[temp[i].parentId].children = []; } temp[temp[i].parentId].children.push(temp[i]); } else { treeData.push(temp[i]); } } return treeData; } // 2 function convert(list) { const res = [] const map = list.reduce((res, v) => (res[v.id] = v, res), {}) for (const item of list) { if (item.parentId === 0) { res.push(item) continue } if (item.parentId in map) { const parent = map[item.parentId] parent.children = parent.children || [] parent.children.push(item) } } return res } // 3 const convert = list => { let map = new Map(); let result = [] list.forEach(el => { map.set(el.id, el); }); list.forEach(el => { let parent = map.get(el.parentId); if (!parent) { // parentId === 0 el.children = [] return } if (parent.hasOwnProperty('children')) { parent.children.push(el); } else { parent['children'] = []; parent.children.push(el); } }); for (let i = 0; i < list.length; i++) { const el = list[i]; if (el.parentId === 0) { result.push(el) } } return result }; 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 } ]; convert(list)