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},
]
[
{
"id": 1,
"name": "部门1",
"pid": 0,
"children": [
{
"id": 2,
"name": "部门2",
"pid": 1,
"children": []
},
{
"id": 3,
"name": "部门3",
"pid": 1,
"children": [
]
}
]
}
]
const getChildren = (data,result,pid) => {
for(let item in data) {
if(item.pid === pid) {
let itemInfo = {
...item,
children:[]
}
result.push(itemInfo)
getChildren(data,itemInfo.children,itemInfo.id)
}
}
}
let arrayToTree = (data,pid) => {
let result = [];
getChildren(data,result,pid)
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},
]
const foo = (arr) => {
const result = { }
const ret = []
arr.forEach((item) => {
const { pid } = item
if (result[pid]) result[pid].push(item)
else result[pid] = [item]
})
ret.push(...result['0'])
var fn = (arr) => {
arr.forEach(item => {
const { id } = item
const children = result[id]
if (children) {
item.children = children
fn(children)
}
})
return ret
}
return fn(ret)
}
foo(arr)