Js 代碼遞歸實現樹形數據與數組相互轉換。


貼代碼:

// Grid-》Tree 結構組裝。
var tree = [];
this.setTreeData(table, tree, "");
//組裝樹形
     setTreeData = (source, list, pid) => {
        if (typeof (source) == "undefined") return;
        source.forEach((father) => {
            if (father.PID == pid) {
                list.push(father);
                if (!father.IsLowest) {
                    if (typeof (father.children) == "undefined") {
                        father.children = [];
                    }
                    father.children = this.setTreeData(source, father.children, father.ContractListDtlID);
                }
            }


//Tree -> 數組機構
//樹形數據轉換成grid,調用者自己決定children 屬性刪除與否 2019-
     
var list= [];
this.setGridDataFromTree(list, tree, "");

setGridDataFromTree= function(list,dataSource){
        if (!(Array.isArray(dataSource) && dataSource.length >0)) return ;            
        dataSource.forEach((father) => {
            // debugger;
            list.push(father);            
            if (typeof (father.children) == "undefined") {                
            } else {                
                this.setGridDataFromTree(list, father.children);
            }
        });
        // return;
    }
        })
        return list;
    }

 如上代碼在開發React項目, 用到內容。
需要注意的是, Gird 與Tree 結構轉換是一個引用賦值。 也就是說改gird 或者treeData之后 值會影響變。
不需要的話,深拷貝之后再轉。
淺拷貝的好處就是利用引用特性, 改treeData 值界面保存后去gridData 是可以的, 減少了TreeData -》 GridData 操作。
當然控件本身需要額外增加這種判斷,來做顯示界面刷新。

 shouldComponentUpdate(newProps, newState) {
        if (newProps.tableData !== this.props.tableData 
            || JSON.stringify(newProps.tableData) !== JSON.stringify(this.props.tableData)) {
            this.loadData(newProps);
     
        }
        // debugger;
        return true;
    }


免責聲明!

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



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