title: Getting hierchical data from redis with node.js
body: <p>I was hoping that someone out there could come to my rescue with this.  For some reason, I can't get my mind around recursion in node.js.  It doesn't even have to be recursion, if there's another way.</p>
  
  <p>I'm using redis sets to store a hierarchy in sets:  </p>
  
  <pre><code>SADD parents.&lt;name&gt; &lt;parent1&gt; &lt;parent2&gt;
  </code></pre>
  
  <p>then, parent1 and parent2 will also have entries, and on up.  I want to convert it to a JSON array of objects.</p>
  
  <p>The JSON will look like this:</p>
  
  <pre><code>[
   {
       label: &lt;name&gt;,
       parents: [
           { label: &lt;parent1&gt;,
             parents: [ {label: &lt;grandparent1&gt;}] },
           { label: &lt;parent2&gt; }
       ]
   }
  ]
  </code></pre>
  
  <p>And so on and so forth.  This should be able to work for any depth, although on average it will only be 4-6 nodes deep.</p>
  
  <p>Here's some code I've been playing with that just gets me the first level:</p>
  
  <pre><code>var redis = require('node-redis');
  var r_client = redis.createClient();
  
  function get_parents (name, current, cb) {
  
          var output = new Array;
          output.push( { label: name, parents: [] } );
  
          r_client.smembers('parents.' + name, function(err, reply) {
              for (var i = 0; i &lt; reply.length; i++)
              {
                  var name = reply[i].toString('utf8');
                  output[i].parents.push({label: name, parents: [] });
               }
               cb (output);
          });
  }
  
  get_parents( 'bob', function(out) {console.log('Final output: ' + JSON.stringify( out ))} );
  </code></pre>
  
  <p>I'm basically wanting to do this:</p>
  
  <ul>
  <li>Start at root node. Call redis, get parents. </li>
  <li>Build object for root
  node.</li>
  <li>Call same function to build the other objects.</li>
  <li>As calls to redis begin to come back null, the calls will return and start to combine objects.</li>
  </ul>
  
  <p>Any help would be greatly appreciated.</p>
  
  <p>EDIT: Updated get_parents (still doesn't work):</p>
  
  <pre><code>function get_parents (name, cb) {
      r_client.smembers('parents.' + name, function(err, reply) {
      for (var i = 0; i &lt; reply.length; i++)
      {
        var name = reply[i].toString('utf8');
        output.push( { label: name, parents: [] } );
        output[i].parents = get_parents (output[i].parents.name, cb);
      }
  
      cb (output);
    });
  }
  </code></pre>
  
  <p>EDIT:  I decided to use Promises, so <a href="https://stackoverflow.com/questions/18904745/understanding-promises-in-node-js-for-recursive-function">I pursued that option</a>.  Thanks for all the help!</p>