JS樹結構轉list結構


樹轉list

    /**
     * 樹轉list
     */
    function treeToList(tree){
        for(var i in tree){
            var node = tree[i];
            list = [];  //結果lsit
            if (node.children.length !== 0) {  //遍歷樹的第一層,只有一個根結點
                //第一層加入到list中,因為根結點模塊設置為虛擬結點,所以不用加入
                /*list.push({
                    id: node.id,
                    name: node.title,
                    parentId:node.parentId
                });*/
                toListDF(node.children, list, node.id);  //遍歷子樹,並加入到list中.
            }
        }
        return list;
    }

    /**
     * 深度優先遍歷樹
     * 一個遞歸方法
     * @params tree:要轉換的樹結構數據
     * @params list:保存結果的列表結構數據,初始傳list = []
     * @params parentId:當前遍歷節點的父級節點id,初始為null(因為根節點無parentId)
     **/
    function toListDF (tree, list, parentId) {
        for (var i in tree) { //遍歷最上層
            //將當前樹放入list中
            var node = tree[i];
            list.push({
                id: node.id,
                name: node.title,
                parentId:parentId
            });
            //如果有子結點,再遍歷子結點
            if (node.children.length !== 0) {
                toListDF(node.children, list, node.id)  //遞歸
            }
        }
    }


免責聲明!

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



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