//通过子级的pid找到父级对应的id,制作树状图
var data = [
{ id: 1, name: "用户管理",other:"我是其他参数1",other2:"我是其他参数2",other3:"我是其他参数3", pid: 0 },
{ id: 2, name: "发货申请",other:"我是其他参数1",other2:"我是其他参数2",other3:"我是其他参数3", pid: 1 },
{ id: 3, name: "兑换申请",other:"我是其他参数1",other2:"我是其他参数2",other3:"我是其他参数3", pid: 1 },
{ id: 4, name: "日志记录",other:"我是其他参数1",other2:"我是其他参数2",other3:"我是其他参数3", pid: 2 },
{ id: 5, name: "系统设置",other:"我是其他参数1",other2:"我是其他参数2",other3:"我是其他参数3", pid: 0 },
{ id: 6, name: "权限管理",other:"我是其他参数1",other2:"我是其他参数2",other3:"我是其他参数3", pid: 5 },
{ id: 7, name: "用户角色",other:"我是其他参数1",other2:"我是其他参数2",other3:"我是其他参数3", pid: 6 },
{ id: 8, name: "菜单设置",other:"我是其他参数1",other2:"我是其他参数2",other3:"我是其他参数3", pid: 6 },
{ id: 9, name: "权限管理",other:"我是其他参数1",other2:"我是其他参数2",other3:"我是其他参数3", pid: 7 },
{ id: 10, name: "用户角色",other:"我是其他参数1",other2:"我是其他参数2",other3:"我是其他参数3", pid: 8 },
{ id: 11, name: "菜单设置",other:"我是其他参数1",other2:"我是其他参数2",other3:"我是其他参数3", pid: 10 },
];
建立一个公用的函数方法,将数据存储为以ID为KEY的map索引数据列
function toEleTreeData(data) {
// 删除 所有 children,以防止数据出现异常(看情况可以不要这步)
data.forEach(function (item) {
delete item.children;
});
// 将数据存储为以 id 为 KEY 的 map 索引数据列
var map = {};
data.forEach(function (item) {
item.Children = [] // 看情况加这一步
map[item.id] = item;
});
//console.log(map);
var DataInfo = [];
data.forEach(function (item) {
//如果需要对特定字段进行处理,那么这里做对应处理,会存在一定数据冗余
//item.label = item.name;
// 以当前遍历项,的pid,去map对象中找到索引的id
var parent = map[item.pid];
// 如果找到索引,那么说明此项不在顶级当中,那么需要把此项添加到,他对应的父级中
if (parent) {
(parent.children || ( parent.children = [] )).push(item);
parent.Children.push(item) //看情况要这一步,不要上一步
} else {
//如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中,作为顶级
DataInfo.push(item);
}
});
return DataInfo;
}
console.log(toEleTreeData(data))