title: How to do a recursive search of this Javascript/JSON tree?
body: <p>I'm writing some Javascript code. I have a JSON object that looks like this (spacing modified for readability):</p>
  
  <pre><code>var myNodes = [
      {
          id: 4, 
          children: [
              {
                  id: 1, 
                  children: [
                  ]
              },
              {
                  id: 3, 
                  children: [
                  ]
              }
          ]
      },
      {
          id: 2, 
          children: [
          ]
      },
      {
          id: 6, 
          children: [
              {
                  id: 5, 
                  children: [
                  ]
              }
          ]
      }
  ]
  </code></pre>
  
  <p>Each node's id in this data structure is unique. 
  However, other than that, there is no fixed or known relationship amongst the ID numbers at all. 
  And there is no limit to the number of children at each level.</p>
  
  <p>If I want search this tree and return the node with id == 6. How can I do it?
  I have written the following code, however after it encounters the first leaf node the entire algorithm returns false, which is clearly not right. I'm just trying to do a basic depth-first-search. But I don't want to add extra fields to this data and "mark" the nodes as I have seen in some DFS implementations on the web.</p>
  
  <pre><code>myClass.prototype.nodeSearch = function nodeSearch(treeNodes, searchID){
      for (var nodeIdx = 0; nodeIdx &lt;= treeNodes.length-1; nodeIdx++)
      {
          console.log("Comparing treeNodes element with ID==" + treeNodes[nodeIdx].id + " to SearchID==" + searchID);
          if (treeNodes[nodeIdx].id == searchID)
          {    
              console.log("Match!");
              return treeNodes[nodeIdx];
          }
          else
          {
              console.log("No Match! Trying " + treeNodes[nodeIdx].children.length + " Children of Node ID#" + treeNodes[nodeIdx].id);
              return this.nodeSearch(treeNodes[nodeIdx].children, searchID); 
          }
      }
      console.log("Done trying " + treeNodes.length + " children. Returning False");
      return false;
  };
  </code></pre>