let arr = [
{id: 1, name: 'test1', pid: 0},
{id: 2, name: 'test2', pid: 1},
{id: 3, name: 'test3', pid: 2},
{id: 4, name: 'test4', pid: 3},
{id: 5, name: 'test5', pid: 2},
];
递归的方式
function fn(data,pid){
function tree(id) {
let arr = []
data.filter(item => {
return item.pid === id;
}).forEach(item => {
arr.push({
id: item.id,
name: item.name,
pid: item.pid
children: tree(item.id)
})
})
return arr
}
return tree(pid) // 第一级节点的父id,是null或者0,视情况传入
}
fn(arr, 0);
引用内存
function fn(arr){
let map = {};
let tree = [];
arr.forEach(item => {
map[item.id] = item;
});
arr.forEach(item => {
if (item.pid) {
if (!map[item.pid].child) {
map[item.pid].child = [];
}
map[item.pid].child.push(item);
} else {
tree.push(item);
}
});
return tree;
}
fn(arr);