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;
    }

猜你喜欢

转载自www.cnblogs.com/hijushen/p/11103995.html