树形数据
let list = [
{
id: 1,
pid: 0,
path: '/home',
title: '首页',
name: 'Home'
},
{
id: 2,
pid: 0,
path: '/student',
name: 'Student',
title: '招生管理'
},
{
id: 100,
pid: 2,
path: 'plan',
link: '/student/plan',
title: '开班计划',
name: 'StudentPlan'
},
{
id: 101,
pid: 2,
path: 'customer',
link: '/student/customer',
title: '意向客户',
name: 'StudentCustomer'
},
{
id: 102,
pid: 2,
path: 'list',
link: '/student/list',
title: '客户列表',
name: 'StudentList'
},
{
id: 3,
pid: 0,
path: '/system',
title: '系统管理',
name: 'System'
},
{
id: 103,
pid: 3,
path: 'user',
link: '/system/user',
title: '用户管理',
name: 'SystemUser'
},
{
id: 104,
pid: 3,
path: 'department',
link: '/system/department',
title: '部门管理',
name: 'SystemDepartment'
},
{
id: 105,
pid: 3,
path: 'anth',
link: '/system/anth',
title: '部门管理',
name: 'SystemAnth'
},
{
id: 4,
pid: 0,
path: '/info',
title: '信息管理',
name: 'Info'
},
{
id: 106,
pid: 4,
path: 'anth',
link: '/info/type',
title: '信息类型',
name: 'InfoType'
},
{
id: 1001,
pid: 106,
path: 'publish',
link: '/info/type/publish',
title: '发布信息',
name: 'InfoTypePublish'
}
];
递归处理无限子级数据
console.log(formateDataTree(list));
function formateDataTree (data) {
let parents = data.filter(item => item.pid === 0),
children = data.filter(item => item.pid !== 0);
dataToTree(parents, children);
return parents;
function dataToTree (parents, children) {
parents.map(p => {
children.map((c, i) => {
if (c.pid === p.id) {
let _children = JSON.parse(JSON.stringify(children));
_children.splice(i, 1);
dataToTree([c], _children);
if (p.children) {
p.children.push(c);
} else {
p.children = [c];
}
}
});
});
}
}
非递归扁平化处理
console.log(formateDataTree(list));
function formateDataTree(data) {
let _data = JSON.parse(JSON.stringify(data));
return _data.filter(p => {
const _arr = _data.filter(c => c.pid === p.id);
_arr.length && (p.children = _arr);
return p.pid === 0;
});
}
reduce处理数据
console.log(formateDataTree(list));
function formateDataTree (data) {
// info 为对象,以每一项的 id 为 key, 并且为每个对象添加 children 属性
let info = data.reduce((acc, cur, idx) => {
return (acc[cur.id] = cur, acc);
}, {});
return data.filter(item => {
// 将非根节点的 info 下的 item 继续遍历 —— 为当前项寻找父节点
if (info[item.pid]) { // info[0]不存在, 并且还找到该节点的父节点
// 将对应的 item 放入对应的对象里面去,因为它是浅拷贝,所以会影响原来的数组,进而组装成一个树结构
// 将 pid 相同的项,全部 push 到
if (info[item.pid].children) {
info[item.pid].children.push(item);
} else {
info[item.pid].children = [item];
}
}
// 将 pid 为 0 的 item 返回
return !item.pid;
});
}
参考资料
js 将数组列表转为树结构
JavaScript『树形数据结构化』【笔面试必备】