0
\$\begingroup\$

I wrote the method below, and was wondering whether a better way exists/best practice tips

_objectIsDefined = function (obj, path) {
  if (typeof path !== 'undefined') {
    // if we have been given a specific object path then recursively search it
    var pathSplit = path.split("."),
      scope = undefined;
    scope = obj;
    for (i = 0; i < pathSplit.length; i++) {
      if (typeof scope[pathSplit[i]] === 'undefined') {
        return false;
      } else if (i == pathSplit.length - 1 && typeof scope[pathSplit[i]] !== 'undefined') {
        return true;
      }
      scope = obj[pathSplit[i]];
    }
    return false;
  } else if (typeof obj !== 'undefined') {
    // if we've just been given an object and no path then return whether
    // its defined or not...
    return true;
  } else {
    return false;
  }
}
 // Usage
var isDefined = _objectIsDefined(myObject);
var isDefinedDeep = _objectIsDefined(myObject, "somenested.child.property.name");
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

First of all, what you are doing is not recursive (self-calling). It's iterative (looping).

And here's a shorter version of it:

_objectIsDefined = function (obj, path) {

  if (!obj) return false;           // no object, return false
  if (obj && !path) return true;    // has object, no path, return true

  // I suggest var per variable for clarity
  var props = path.split(".");
  var currentObject = obj;

  for (var i = 0; i < props.length; ++i) {
    //store the next property, evaluate and break out if it's undefined
    currentObject = currentObject[props[i]];
    if (!currentObject) return false;
  }

  // If the loop did not break until the last path, then the path exists
  return true;
}
\$\endgroup\$
1
  • \$\begingroup\$ My mistake - thanks for the correction on semantics. :) Enjoying the optimization you have performed, works great. \$\endgroup\$
    – Phil
    Oct 14, 2013 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.