JavaScript recursive search in JSON object

后端 未结 6 501
野趣味
野趣味 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:26

    When searching recursively, you have to pass the result back by returning it. You're not returning the result of findNode(id, currentChild), though.

    function findNode(id, currentNode) {
        var i,
            currentChild,
            result;
    
        if (id == currentNode.id) {
            return currentNode;
        } else {
    
            // Use a for loop instead of forEach to avoid nested functions
            // Otherwise "return" will not work properly
            for (i = 0; i < currentNode.children.length; i += 1) {
                currentChild = currentNode.children[i];
    
                // Search in the current child
                result = findNode(id, currentChild);
    
                // Return the result if the node has been found
                if (result !== false) {
                    return result;
                }
            }
    
            // The node has not been found and we have no more options
            return false;
        }
    }
    

提交回复
热议问题