1.用parentId的数据格式转换成有children的数据
var array = []; var iterator1 = function (treeNodes) { if (!treeNodes || !treeNodes.length) return; var parent,i = 0,obj = {}; while(i < treeNodes.length ){ node = treeNodes[i++]; obj[node.id] = node; if(node.parentId){ parent = obj[node.parentId]; if(parent.children){ node["parIndex"] = parent.parIndex +"."+ (parent.children.length + 1); node.cell[0] = node["parIndex"]; parent.children.push(node); }else{ node["parIndex"] = parent.parIndex +"."+ 1; node.cell[0] = node["parIndex"]; parent.children = [node]; } }else{ node["parIndex"] = 1; array.push(node); } } return array; }; console.log('------------- 递归 ------------------'); iterator1(treeNodes);
2.将有children的数据拆成平级对象(非递归深度优先)(1 1.1 1.2 2 ...)
var array1 = []; var iterator2 = function (treeNodes) { var stack = []; if (!treeNodes || !treeNodes.length) return; //先将第一层节点放入栈 for (var i = 0, len = treeNodes.length; i < len; i++) { stack.push(treeNodes[i]); } var item; while (stack.length) { item = stack.shift(); console.log(item.id); //如果该节点有子节点,继续添加进入栈顶 if (item.children && item.children.length) { stack = item.children.concat(stack); } delete item.children; delete item.parIndex; array1.push(item); } }; console.log('------------- 非递归深度优先实现 ------------------'); iterator2(array);
3.非递归广度优先(1 2 1.1 1.2 ...)
//非递归广度优先实现 var iterator1 = function (treeNodes) { var stack = []; if (!treeNodes || !treeNodes.length) return; //先将第一层节点放入栈 for (var i = 0, len = treeNodes.length; i < len; i++) { stack.push(treeNodes[i]); } var item; while (stack.length) { item = stack.shift(); console.log(item.id); //如果该节点有子节点,继续添加进入栈底 if (item.children && item.children.length) { stack = stack.concat(item.children); } } }; console.log('------------- 非递归广度优先实现 ------------------'); iterator1(treeNodes);
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。