https://juejin.cn/post/6983904373508145189
<script> 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: [], } console.log('c:'); } console.log('!itemMap['+id+']:'+JSON.stringify(itemMap[id])); itemMap[id] = { id:item.id, name:item.name, pid:item.pid, children: 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; } 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}, ] var res=arrayToTree(arr); console.log(JSON.stringify(res)); </script>
一片空白 5.8万
父爱如山,不善表达。回想十多年前,总记得父亲有个宽厚的肩膀,小小的自己跨坐在上面,越过人山人海去看更广阔的天空,那个时候期望自己有一双翅膀,能够像鸟儿一样飞得高,看得远。虽然父亲有时会和自己开玩笑,但在做错事的时候会受到严厉的训斥。父亲有双粗糙的大手掌。