user825286
user825286

Reputation:

Recursive loop until we're done with the object [JS]

I"m building a plugin for Photoshop, which is based on layers. To do this, I need to build an array with each layer which returns true when going through a function (checking the name for matches).

How could I basically "recursively" go through the object, and child objects, until I've been through everything? (Putting "selected" items in an array in the process).

The object is just a plain javascript object, with tons of objects in it (and further more inside it).

Upvotes: 0

Views: 391

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 600126

Something like this, but it's missing lots of checks for now:

function showProperties(object, prefix) {
    if (typeof prefix == "undefined") prefix = "";
    var result = ""
    for (property in object) {
        result += prefix + property+"="+object[property]+" "+typeof object[property]+"\n";
        if (typeof object[property] == "object") {
            result += showProperties(object[property], prefix+"  ");
        }
    }
    return result;
}

Upvotes: 1

gztomas
gztomas

Reputation: 3260

Try this:

var isASelectedLayer = function(element) {
    ...
}
var objectWithLayers = {...}

var selected = [];
var lookForSelectedLayers = function(o) {
    for(element in o) {
        if(isASelectedLayer(o[element]))
            selected.push(o[element]);
        else
            lookForSelectedLayers(o[element]);
    }
};
lookForSelectedLayers(objectWithLayers);

Upvotes: 1

Related Questions