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.
I'm using redis sets to store a hierarchy in sets:
SADD parents.<name> <parent1> <parent2>
then, parent1 and parent2 will also have entries, and on up. I want to convert it to a JSON array of objects.
The JSON will look like this:
[
{
label: <name>,
parents: [
{ label: <parent1>,
parents: [ {label: <grandparent1>}] },
{ label: <parent2> }
]
}
]
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.
Here's some code I've been playing with that just gets me the first level:
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 < 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 ))} );
I'm basically wanting to do this:
- Start at root node. Call redis, get parents.
- Build object for root node.
- Call same function to build the other objects.
- As calls to redis begin to come back null, the calls will return and start to combine objects.
Any help would be greatly appreciated.
EDIT: Updated get_parents (still doesn't work):
function get_parents (name, cb) {
r_client.smembers('parents.' + name, function(err, reply) {
for (var i = 0; i < 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);
});
}
EDIT: I decided to use Promises, so I pursued that option. Thanks for all the help!