title: Tree traversal in javascript
body: <p>I am trying to generate URLs for pages stored in a MongoDB in node.</p>
  
  <p>Using the following function I want to traverse a javascript object that and display the path to each element.<br /></p>
  
  <p>I am nearly there, but I am stuck - There might even be a better way to do this using using Async (which I must admit, confuses me a bit).</p>
  
  <p><strong>Function: (<a href="http://jsfiddle.net/cT8wn/1/" rel="nofollow">demo</a>)</strong></p>
  
  <pre><code>function printTree(people, slug) {
      for (var p = 0; p &lt; people.length; p++) {
          var root = people[p];
          slug = slug + root.name + "/";
          console.log(slug);
          if (root.children.length &gt; 0) {
              var childrenCount = root.children.length;
              for (var c = 0; c &lt; childrenCount; c++) {
                  if (root.children[c].children.length &gt; 0) {
                      printTree(root.children[c].children, slug + root.children[c].name + "/");
                  }
              }
          }
      }
  };
  </code></pre>
  
  <p><strong>Output:</strong></p>
  
  <pre><code>/michael/
  /michael/angela/oscar
  /michael/meredith/creed
  /michael/meredith/creed/kelly
  </code></pre>
  
  <p><strong>Expected Output:</strong></p>
  
  <pre><code>/michael/
  /michael/angela/
  /michael/angela/oscar/
  /michael/meredith/
  /michael/meredith/creed/
  /michael/meredith/kelly/
  </code></pre>
  
  <p><strong>Object:</strong></p>
  
  <pre><code>[
    {
      "name": "michael",
      ...
      "children": [
        {
          "name": "angela",
          ...
          "children": [
            {
              "name": "oscar",
              ...
              "children": []
            }
          ]
        },
        {
          "name": "meredith",
          ...
          "children": [
            {
              "name": "creed",
              ...
              "children": []
            },
            {
              "name": "kelly",
              ...
              "children": []
            }
          ]
        },
        { ... }
      ]
    }
  ]
  </code></pre>
  
  <p>If it helps, the data is stored using nested sets: <a href="https://github.com/groupdock/mongoose-nested-set" rel="nofollow">https://github.com/groupdock/mongoose-nested-set</a>
  So there might be a better way to do the above work using nested sets (negating the above object).</p>