JavaScript recursive search in JSON object

后端 未结 6 492
野趣味
野趣味 2020-11-30 04:21

I am trying to return a specific node in a JSON object structure which looks like this

{
    \"id\":\"0\",
    \"children\":[
        {
            \"id\":\"         


        
6条回答
  •  天涯浪人
    2020-11-30 04:44

    function findNode(id, currentNode) {
    
        if (id == currentNode.id) {
            return currentNode;
        } else {
            var result;
            currentNode.children.forEach(function(node){
                if(node.id == id){
                    result = node;
                    return;
                }
            });
            return (result ? result : "No Node Found");
        }
    }
    console.log(findNode("10", node));
    

    This method will return the node if it present in the node list. But this will loop through all the child of a node since we can't successfully break the forEach flow. A better implementation would look like below.

    function findNode(id, currentNode) {
    
        if (id == currentNode.id) {
            return currentNode;
        } else {
            for(var index in currentNode.children){
                var node = currentNode.children[index];
                if(node.id == id)
                    return node;
                findNode(id, node);
            }
            return "No Node Present";
        }
    }
    console.log(findNode("1", node));
    

提交回复
热议问题