ztree 数组和树结构互转算法



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

 上面直接贴了 Ztree 把数据库列表项 转换成树结构的方法,在以前思维中,一说道这把列表项转换成树就是用递归,还可以用这种方式来实现的。学习了。

你可能感兴趣的:(ztree)