父子节点表示法转换成树表示法 function arrayToTree(nodes, setting) { var idKey = setting.idKey, pIdKey = setting.pIdKey, childKey = setting.childKey; var result = [], // 保存结果 nodesForId = {}; // 存放中间结果 // 转换
function arrayToTree(nodes, setting) { var idKey = setting.idKey, pIdKey = setting.pIdKey, childKey = setting.childKey; var result = [], // 保存结果 nodesForId = {}; // 存放中间结果 // 转换为属性名放置节点 nodes.forEach(function (node) { var id = node[idKey]; nodesForId[id] = node; }); nodes.forEach(function (node) { var id = node[idKey], // 节点id pId = node[pIdKey], // 节点父id pNode = nodesForId[pId]; // 根据节点父id找出父节点 if (pNode && id != pId) { // 父节点存在并且或者父节点不等于本节点 if (!pNode[childKey]) pNode[childKey] = []; pNode[childKey].push(node); } else { // 如果父节点不存在,则该节点是根节点,插入根数组 result.push(node); } }); return result; }树表示法转换成父子节点表示法
function treeToArray(nodes, setting, pId) { var idKey = setting.idKey, pIdKey = setting.pIdKey, childKey = setting.childKey; var result = [], // 保存结果 fn = arguments.callee; nodes.forEach(function (node) { var childNodes = node[childKey], id = node[idKey]; if (pId) node[pIdKey] = pId; result.push(node); if (childNodes) { var arr = fn(childNodes, setting, id); // 由于每次调用函数都经过一次result=[],因此需要调用concat来合并结果 result = result.concat(arr); } }); return result; }