// 自动寻找顶级节点
function getTree(items) {
var ids = items.map(e => e.id);
let pids = items.filter(e => !ids.includes(e.pid));
let index = 0;
return pids.map(e => {
e.level = index;
e.children = handler(items, e.id, index + 1);
return e
});
}
// 返回指定pid节点的子级
function handler(items, pid, index) {
var _arr = [];
items.forEach(item => {
if (pid === item.pid) {
item.level = index + 1;
let arr = handler(items, item.id, index + 1);
if (arr.length) item.children = arr;
_arr.push(item);
}
});
return _arr;
}
网友评论