标签:parentId children 广度优先 深度优先
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的数据拆成平级对象(非递归深度优先)
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.非递归广度优先
//非递归广度优先实现 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);
JavaScript之parentId转换成children数据,并解析
标签:parentId children 广度优先 深度优先
原文地址:http://blog.51cto.com/dd118/2095671