Bryce
Bryce

Reputation: 6610

How to recursively get a list of all children in a nested object?

Suppose I have a class that can hold other instances of itself:

function Thing() {
    this.subThings = [];
}

And I add n subThings to the top thing:

var rootThing = new Thing();

rootThing.subThings.push(new Thing());
rootThing.subThings.push(new Thing());
rootThing.subThings.push(new Thing());

And then I add n subThings to some of the rootThing's subThings:

rootThing.subThings[0].subThings.push(new Thing());
rootThing.subThings[0].subThings.push(new Thing());
rootThing.subThings[0].subThings.push(new Thing());

At this point, the structure looks like this:

rootThing
|
+--subThing
|  |
|  +--subThing
|  |
|  +--subThing
|  |
|  +--subThing
|
+--subThing
|
+--subThing

So, how can I get a list of all the subThings and all of their subThings in rootThing?

function getAllChildren(beginNode) {
    var allChildren = [];

    beginNode.subThings.forEach(function(childNode) {
        allChildren.push(childNode);
        // allChildren = allChildren.concat(childNode.subThings); // something along these lines
    });

    return allChildren;
}

console.log(getAllChildren(rootThing));

Upvotes: 0

Views: 591

Answers (2)

Bryce
Bryce

Reputation: 6610

With thanks to @zerkms, here is a working implementation:

function getAllChildren(beginNode) {
    var allChildren = beginNode.subThings;

    beginNode.subThings.forEach(function(childNode) {
        allChildren = allChildren.concat(getAllChildren(childNode));
    });

    return allChildren;
}

Upvotes: 1

Brian
Brian

Reputation: 1553

Are you looking for something like this?

var GetAllThings = function(Thing thing) {
    var result = [];

    //Assume you want to remove the subthings as you flatten
    var subthings = thing.subthings;
    thing.subThings = null;

    result.push(thing);

    for(var i = 0; i < subthings i++) {
        result.concat(GetAllThings(subthings[i]));
    }

    return result;
};

This will basically flatten the tree, but if you just want to see/process it, the above comments are correct in that you can just handle this as a json object.

Upvotes: 0

Related Questions