js數組和樹互轉


1. 數組轉樹

const arr = [
    {id:1, parentId: null, name: 'a'},
    {id:2, parentId: null, name: 'b'},
    {id:3, parentId: 1, name: 'c'},
    {id:4, parentId: 2, name: 'd'},
    {id:5, parentId: 1, name: 'e'},
    {id:6, parentId: 3, name: 'f'},
    {id:7, parentId: 4, name: 'g'},
    {id:8, parentId: 7, name: 'h'},
]

1.1 利用map存儲數組項,空間換時間

function array2Tree(arr){
    if(!Array.isArray(arr) || !arr.length) return;
    let map = {};
    arr.forEach(item => map[item.id] = item);

    let roots = [];
    arr.forEach(item => {
        const parent = map[item.parentId];
        if(parent){
            (parent.children || (parent.children=[])).push(item);
        }
        else{
            roots.push(item);
        }
    })

    return roots;
}

1.2 利用遞歸

//需要插入父節點id,pid為null或'',就是找root節點,然后root節點再去找自己的子節點
function array2Tree(data, pid){
    let res = [];
    data.forEach(item => {
        if(item.parentId === pid){
            let itemChildren = array2Tree(data,item.id);
            if(itemChildren.length) item.children = itemChildren;
            res.push(item);
        }
    });
    return res;
}  

2. 樹轉數組

2.1 深度優先遍歷

function dfs(root,fVisit){
    let stack = Array.isArray(root) ? [...root] : [root];
    while(stack.length){
        let node = stack.pop();
        fVisit && fVisit(node);
        let children = node.children;
        if(children && children.length){
            for(let i=children.length-1;i>=0;i--) stack.push(children[i]);
        }
    }
}

2.2 廣度優先遍歷

function bfs(root,fVisit){
    let queue = Array.isArray(root) ? [...root] : [root];
    while(queue.length){
        let node = queue.shift();
        fVisit && fVisit(node);
        let children = node.children;
        if(children && children.length){
            for(let i=0;i<children.length;i++) queue.push(children[i]);
        }
    }
}

3. 驗證

//驗證數組轉樹
let a = array2Tree(arr,null);
console.log(a);

//驗證樹轉數組
let a1 = [];
bfs(a,node => a1.push(node));
console.log(a1);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM