ztree 数组和树结构互转算法
阅读原文时间:2023年07月11日阅读:1

//树转化为数组
transformToArrayFormat: function (setting, nodes) {
if (!nodes) return [];
var childKey = setting.data.key.children,
r = [];
if (tools.isArray(nodes)) {
for (var i=0, l=nodes.length; i<l; i++) {
r.push(nodes[i]);
if (nodes[i][childKey])
r = r.concat(data.transformToArrayFormat(setting, nodes[i][childKey]));
}
} else {
r.push(nodes);
if (nodes[childKey])
r = r.concat(data.transformToArrayFormat(setting, nodes[childKey]));
}
return r;
},
//数组转化为树
transformTozTreeFormat: function(setting, sNodes) {
var i,l,
key = setting.data.simpleData.idKey,
parentKey = setting.data.simpleData.pIdKey,
childKey = setting.data.key.children;
if (!key || key=="" || !sNodes) return [];

        if (tools.isArray(sNodes)) {  
            var r = \[\];  
            var tmpMap = \[\];  
            for (i=0, l=sNodes.length; i<l; i++) {  
                tmpMap\[sNodes\[i\]\[key\]\] = sNodes\[i\];  
            }  
            for (i=0, l=sNodes.length; i<l; i++) {  
                if (tmpMap\[sNodes\[i\]\[parentKey\]\] && sNodes\[i\]\[key\] != sNodes\[i\]\[parentKey\]) {  
                    if (!tmpMap\[sNodes\[i\]\[parentKey\]\]\[childKey\])  
                        tmpMap\[sNodes\[i\]\[parentKey\]\]\[childKey\] = \[\];  
                    tmpMap\[sNodes\[i\]\[parentKey\]\]\[childKey\].push(sNodes\[i\]);  
                } else {  
                    r.push(sNodes\[i\]);  
                }  
            }  
            return r;  
        }else {  
            return \[sNodes\];  
        }  
    }