PS7/CS/CS2 getByName and getAllByName

Photoshop Script Snippets - Note: Full Scripts go in the Photoshop Scripts Forum

Moderators: Tom, Kukurykus

xbytor

PS7/CS/CS2 getByName and getAllByName

Post by xbytor »

Photoshop has containers with some interesting characteristics. One of them is that the 'getByName' methods will throw an exception if an item with the specified name is not found. This is more than a little lame but easy enough to fix.
To make matters worse, PS7 doesn't even have the lame 'getByName' methods.

So, I've written up a getByName that
1) returns 'undefined' if the desired thing isn't in the container
2) can return ALL of the elements that match the name
3) can match via RegExps instead of doing just a simple exact match

I've also added a 'getAllByName' wrapper to help me keep things straight in my code.

These two methods work without change on all of the magic PS containers. I've posted similar code on adobeforums. This is the new and improved version.

Code: Select all//
// Return an item called 'name' from the specified container.
// This works for the "magic" on PS containers like Documents.getByName(),
// for instance. However this returns null if an index is not found instead
// of throwing an exception
// The 'all' arg is optional and defaults to 'false'
//
function getByName(container, name, all) {
  // check for a bad index
  if (!name) throw "'undefined' is an invalid name/index";

  var matchFtn;

  if (name instanceof RegExp) {
    matchFtn = function(s1, re) { return s1.match(re) != null; }
  } else {
    matchFtn = function(s1, s2) { return s1 == s2;  }
  }

  var obj = [];

  for (var i = 0; i < container.length; i++) {
    if (matchFtn(container.name, name)) {
      if (!all) {
        return container;     // there can be only one
      }
      obj.push(container);    // add it to the list
    }
  }

  return all ? obj : undefined;
}

//
// Returns all items in the container with the specified name.
//
function getAllByName(container, name) {
  return getByName(container, name, true);
}