递归处理后端传来的数据,处理成能使用的vue路由格式
// 递归处理后端传来的数据,处理成能使用的vue路由格式
// pid为0代表一级路由,pid如果和pid为0的id相等的话代表二级路由... 以此类推...
var arr = [
{ "pid": 0, "id": 3, "name": "最外层3" },
{ "pid": 0, "id": 4, "name": "最外层4" },
{ "pid": 4, "id": 5, "name": "最外层-4" },
{ "pid": 5, "id": 6, "name": "最外层-4-1" },
{ "pid": 0, "id": 7, "name": "最外层7" },
{ "pid": 7, "id": 8, "name": "最外层-7" },
{ "pid": 0, "id": 9, "name": "最外层9" },
{ "pid": 9, "id": 10, "name": "最外层9-1" },
{ "pid": 9, "id": 11, "name": "最外层9-2" },
{ "pid": 11, "id": 12, "name": "最外层9-2-1" }
];
var map = {};
arr.forEach(function (item) {
map[item.id] = item;
});
console.log(map,'map')
var newData = [];
arr.forEach(function (item) {
// 根据当前遍历对象的pid,去map对象中找到对应索引的id
var parent = map[item.pid];
if (parent) {
// 如果找到索引,那么说明此项不在顶级当中,那么需要把此项添加到,他对应的父级中
(parent.children || (parent.children = [])).push(item);
} else {
//如果没有在map中找到对应的索引ID,那么直接把当前的item添加到newData结果集中作为顶级
newData.push(item);
}
});
console.log(newData,'newData')
var array = [
{"pid":0,"id":3,"name":"最外层3"},
{"pid":0,"id":4,"name":"最外层4"},
{"pid":4,"id":5,"name":"最外层-4"},
{"pid":5,"id":6,"name":"最外层-4-1"},
{"pid":0,"id":7,"name":"最外层7"},
{"pid":7,"id":8,"name":"最外层-7"},
{"pid":0,"id":9,"name":"最外层9"},
{"pid":9,"id":10,"name":"最外层9-1"},
{"pid":9,"id":11,"name":"最外层9-2"},
{"pid":11,"id":12,"name":"最外层9-2-1"}
];
for (let index = 0; index < array.length; index++) {
array[index].children=[]
}
// 遍历出树结构json
function getVal(data, ppKey) {
let temp = ppKey ? data[ppKey] : data
for (let key in temp) {
if (!(temp[key] instanceof Object) && key === 'id') {
data.forEach(function (item) {
if (item.pid === temp.id) {
temp.children.push(item)
}
})
}
if (temp[key] instanceof Object || temp[key] instanceof Array) {
getVal(temp, key)
}
}
}
getVal(array)
forSp(array)
// 去除多余的数据
function forSp(data) {
data.forEach(function (item, index) {
// 这里if条件 假如 一级路由的pid全都是0就以此为标识
if (item.pid != 0) {
data.splice(index, 1)
forSp(data)
}
})
}
console.log(array)
Sometimes you need to applaud yourself