2014-11-01 95 views
0

我想遍历一个json文件(一棵树),并给定一个特定的节点,我想保留节点及其所有子节点。我已经尝试编写一些这样做的JavaScript代码,但我得到一个错误“未捕获RangeError:超出最大调用堆栈大小”。这里是我使用的代码:如何遍历json树文件并删除节点?

function removeNodes(tree){ 
    //Check if root node contains any children. 
    if(tree["children"]){ 
     var children = tree["children"]; 
     //Loop through all children and delete their everything further down in their hierarchy. 
     for(var i = 0; i < children.length; i++) { 
      var node = children[i]; 

      var grandChildren = node["children"]; 
      if(grandChildren){ 
       grandChildren.splice(i,1); 
       i--; 
      } 

      removeNodes(node); 
     } 
    } 
} 

我在做什么错在这里?我该如何正确地遍历我的json文件。再次解释一下: 给定一个根节点(本例中为“树”),我想保留根节点及其所有子节点,但删除下面的其他节点。

在此先感谢!

+0

您不使用'tree'参数。你的函数只检查一个特定的值,然后它自己调用,然后再次检查相同的值。 – undefined 2014-11-01 12:32:14

+0

我修正了这个问题,但是我似乎还在循环到无限。我不明白为什么。 – Vanquiza 2014-11-01 12:42:04

+0

树有多大?我知道JavaScript没有适当的尾调用,但似乎不太可能,你会吹你的堆栈,除非树是__very__大或你已经建议它无限递归 – 2014-11-01 12:47:46

回答

0
function removeNodes(tree, desiredNode){  

    //check if node is one we want   
    if (tree == desiredNode) { 
     return tree; 
    } 

    //Check if root node contains any children. 
    if(tree && tree.children){ 
     var children = tree.children; 

     //Loop through all children and delete their everything further down in their hierarchy. 
     for(var i = 0; i < children.length; i++) { 
      var node = removeNodes(children[i], desiredNode); 

      if (node == desiredNode) { 
       return node; 
      } 
     } 
    } 
    return false; //if no match found 
} 

var foo = removeNodes(tree, someNodeToKeep); 
if (foo) { 
    var parent = tree.parentNode; 
    parent.removeChild(tree); 
    parent.appendChild(foo); //parent now contains only that node and children 
} 

请注意,像任何递归函数,这个可以吹上语言堆栈没有适当的尾调用,但除非你使用这个来搜索数据结构应该是罚款。