let arr = [{
id: 1.pid: 0.title: 'home'
}, {
id: 2.pid: 1.title: 'Order List'
}, {
id: 3.pid: 1.title: 'Post Management'
}, {
id: 4.pid: 3.title: 'Post list'
}, {
id: 5.pid: 3.title: 'Post Settings'
}, {
id: 6.pid: 0.title: 'login'
}];
let map;
function arrToMap(arr) {
map = new Map(a);for (let index in arr) {
const item = arr[index];
item.children = [];
map.set(item.id, item)
};
const res = arr.filter(item= > item.pid === 0);
for (let index in arr) {
const item = arr[index];
if (item.pid === 0) continue;
const parent = map.get(item.pid);
parent.children.push(item);
item.parent = parent;
}
return res;
};
console.log(arrToMap(arr))
// Get the corresponding data according to the id
function getTitle(id) {
let list = [];
let items = map.get(id);
while (items) {
list.unshift(items.title);
items = items.parent;
}
return list;
}
console.log(getTitle(5))
Copy the code