Photoshop Javascript to get all layers in the active document

Vigor picture Vigor · Oct 29, 2014 · Viewed 7.6k times · Source

I'm sure it should be discussed before by Photoshop scripters. I write a solution as following. I think it's logically right, but the result is not correct. Anybody can help to check where's wrong in the code, or have ideas for this topic? I want to get all the layers in a document.

Code:

function getAllLayersInLayerSets(layerNodes) {

 var retList = [];

 for (var i=0; i<layerNodes.length; i++) {

    if(layerNodes[i].layerSets.length > 0)
    {
        var tmp = getAllLayersInLayerSets(layerNodes[i].layerSets);

        var j = (tmp == null) ? -1 : tmp.length-1;
        while(tmp && j>=0)
        {
            retList.push(tmp[i]);
            j--;
        }
    }
    for(var layerIndex=0; layerIndex < layerNodes[i].artLayers.length; layerIndex++) 
    {
        var layer=layerNodes[i].artLayers[layerIndex];
        retList.push(layer);
    }

}

return retList;  
}

Many thanks for any help or discussion.

Answer

Javier Aroche picture Javier Aroche · Nov 13, 2015

I know this is an old thread, but this might be useful for someone.

I was looking for a function that would get me all the ArtLayers in a Photoshop comp, including layers nested in groups. The above function was returning undefined, so I modified it and got it to work.

var doc = app.activeDocument;
var allLayers = [];
var allLayers = collectAllLayers(doc, allLayers);

function collectAllLayers (doc, allLayers){
    for (var m = 0; m < doc.layers.length; m++){
        var theLayer = doc.layers[m];
        if (theLayer.typename === "ArtLayer"){
            allLayers.push(theLayer);
        }else{
            collectAllLayers(theLayer, allLayers);
        }
    }
    return allLayers;
}