0

I know I will need to do some type of recursion, but I'm not very experienced with the syntax of js and frameworks. I need to turn the following code into something that will search not just the Children of allNodes, but allNodes.Children[0].Children[0], allNodes.Children[1].Children[0], etc. and return the foundNode.

function findNodeById(id) {

        var foundNode;

        if (id === 0) {        
            foundNode = allNodes[0];
        } else {
            $.each(allNodes[0].Children, function(index, subNode) {
                if (subNode.Id === id) {
                    foundNode = subNode;
                    return false;
                }
            });
        };

        return foundNode;
    }

Here's what the data looks like if that helps: https://gist.github.com/matt-thorp333/09415cb90f8568f145b8b8526fc9ceb0

333Matt
  • 1,124
  • 2
  • 19
  • 29
  • possible duplicate of How to search JSON tree with jQuery - https://stackoverflow.com/questions/5288833/how-to-search-json-tree-with-jquery – sauntimo Jul 20 '17 at 17:54
  • Possible duplicate of [How to search JSON tree with jQuery](https://stackoverflow.com/questions/5288833/how-to-search-json-tree-with-jquery) – Heretic Monkey Jul 20 '17 at 18:42
  • Not a duplicate - this works for objects that are children of the first array element only, as does my code. – 333Matt Jul 20 '17 at 19:19

1 Answers1

0

Add the array as an argument so you can recursively call the function passing in Children array(s)

function findNode(id, arr) {
  var foundNode = false;
  $.each(arr, function(_, item) {
    if (item.Id === id) {
      foundNode = item;
      return false;
    } else if (item.Children && item.Children.length) {
      foundNode = findNode(id, item.Children);
      return !foundNode;
    }
  });
  return foundNode;
}



$.getJSON('https://gist.githubusercontent.com/matt-thorp333/09415cb90f8568f145b8b8526fc9ceb0/raw/fa6404a2f213a4e695826bf4483cb0e2f6859c77/gistfile1.txt', function(data) {
  console.log('Found 0:', !!findNode(0, data)); // should be true
  console.log('Found 2:', !!findNode(2, data)); // should be true
  console.log('Found 3:', !!findNode(3, data));  // should be true
  console.log('Found 19:', !!findNode(19, data)); // should be false
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
charlietfl
  • 170,828
  • 13
  • 121
  • 150