如何遍历json树文件并删除节点?

时间:2014-11-01 12:27:34

标签: javascript json traversal

我正在尝试遍历json文件(树)并给定一个特定节点,我想保留该节点及其所有子节点。我已经尝试编写一些执行此操作的javascript代码,但是我收到错误“Uncaught RangeError:超出最大调用堆栈大小”。这是我使用的代码:

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文件。再次解释: 给定一个根节点(在这种情况下为“树”),我想保留根节点及其所有子节点,但在hiercharchy中删除下面的任何其他内容。

提前致谢!

1 个答案:

答案 0 :(得分: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
}

请注意,与任何递归函数一样,这可能会在没有正确尾调用的情况下对语言进行堆栈,但除非您使用它来搜索大型数据结构,否则它应该没问题。