阅读 234

一维数组转树形数组

let arr = [{
    id: 1, pid: 0, title: '首页'
}, {
    id: 2, pid: 1, title: '订单列表'
}, {
    id: 3, pid: 1, title: '刊登管理'
}, {
    id: 4, pid: 3, title: '刊登列表'
}, {
    id: 5, pid: 3, title: '刊登设置'
}, {
    id: 6, pid: 0, title: '登录'
}];
let map;

function arrToMap(arr) {
    map = new Map();
    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))
// 根据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))
复制代码
文章分类
前端
文章标签