我是歌谣 放弃很容易 但是坚持一定很酷 微信公众号关注小歌谣 日常分享前后端知识
前言
今天来讲一下平常我们做权限系统中的树形结构知识
就是如何把对应关系的结构数据转换为可以一个树形结构
const data = [{id: 2,pid: 0,path: '/course',name: 'Course',title: '课程管理'},{id: 3,name: 'CourseOperate',path: 'operate',link: '/course/operate',pid: 2,title: '课程操作'},{id: 4,name: 'CourseInfoData',path: 'info_data',link: '/course/operate/info_data',pid: 3,title: '课程数据'},{id: 5,name: 'CourseAdd',path: 'add',link: '/course/add',pid: 2,title: '增加课程'},{id: 6,pid: 0,path: '/student',name: 'Student',title: '学生管理',},{id: 7,name: 'StudentOperate',path: 'operate',link: '/student/operate',pid: 6,title: '学生操作'},{id: 8,name: 'StudentAdd',path: 'add',link: '/student/add',pid: 6,title: '增加学生'},{id: 9,name: '123123',path: '234234',link: '/student/add',pid: 8,title: '增加学生'},{id: 10,name: '234234',path: '345345',link: '/student/add',pid: 9,title: '增加学生'},{id: 11,name: '345345',path: '456456',link: '/student/add',pid: 10,title: '增加学生'}
];
数据大概是以上这样的
要给他转换为树形结构
可以开始直接操作了
基本数据
// 树形结构数据结构化/*** [* {id: 2,pid: 0,path: '/course',name: 'Course',title: '课程管理',children: [{id: 3,name: 'CourseOperate',path: 'operate',link: '/course/operate',pid: 2,title: '课程操作',children: [{id: 4,name: 'CourseInfoData',path: 'info_data',link: '/course/operate/info_data',pid: 3,title: '课程数据'}]},{id: 5,name: 'CourseAdd',path: 'add',link: '/course/add',pid: 2,title: '增加课程'}]},* {id: 6,pid: 0,path: '/student',name: 'Student',title: '学生管理',children: [{id: 7,name: 'StudentOperate',path: 'operate',link: '/student/operate',pid: 6,title: '学生操作'},{id: 8,name: 'StudentAdd',path: 'add',link: '/student/add',pid: 6,title: '增加学生'}]}* ]
结构这样
两种方式处理数据
直接上代码 可以自己调试
const treeData = formatDataTree(data);console.log(treeData);// function formatDataTree (data) {
// let parents = data.filter(p => p.pid === 0),
// children = data.filter(c => c.pid !== 0);// dataToTree(parents, children);// return parents;
// // parents childrens array []
// 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];
// }
// }
// });
// })
// }
// }function formatDataTree (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;});
}