\$\begingroup\$
\$\endgroup\$
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");
Joseph
25.4k2 gold badges26 silver badges37 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
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;
}
answered Oct 14, 2013 at 14:14
-
\$\begingroup\$ My mistake - thanks for the correction on semantics. :) Enjoying the optimization you have performed, works great. \$\endgroup\$Phil– Phil2013年10月14日 16:10:42 +00:00Commented Oct 14, 2013 at 16:10
default