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 },
]
// 递归方法
function getChild(data, pid) {
var arr = [];
data.forEach(e => {
if (e.pid === pid) {
e.children = arguments.callee(data, e.id)
arr.push(e)
}
})
return arr;
}
function toTree(arr, pid) {
var tree = []
tree = getChild(arr, pid)
return tree
}
console.log(ToTree2(arr, 0))
//map方式
function ToTree2(items, pidF) {
const result = []; // 存放结果集
const itemMap = {}; //
items.forEach(e => {
const { id, pid } = e;
if (!itemMap[id]) {
itemMap[id] = {
children: [],
}
}
itemMap[id] = {
...e,
children: itemMap[id]['children']
}
if (pid === pidF) {
result.push(itemMap[id]);
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: [],
}
}
itemMap[pid].children.push(itemMap[id])
}
})
return result;
}
console