Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for 'undefined' anywhere in object chain?

I would like to check if any object is missing in complex object chain. I've come up with following solution, is there a better way accomplish the same?

var lg = console.log;
var t = { a:{a1: 33, a12:{ aa1d: 444, cc:3 } }, b:00};
var isDefined = function(topObj, propertyPath) {
    if (typeof topObj !== 'object') {
        throw new Error('First argument must be of type \'object\'!');
    }
    if (typeof propertyPath === 'string') {
        throw new Error('Second argument must be of type \'string\'!');
    }
    var props = propertyPath.split('.');
    for(var i=0; i< props.length; i++) {
        var prp = props[i];
        lg('checking property: ' + prp); 
        if (typeof topObj[prp] === 'undefined') {
            lg(prp + ' undefined!');
            return false;
        } else {
           topObj = topObj[prp];
        }        
    }
    return true;
}
isDefined(t, 'a.a12.cc');
like image 218
krul Avatar asked Dec 26 '22 20:12

krul


1 Answers

You could define your function more simply like this:

var isDefined = function(value, path) {
  path.split('.').forEach(function(key) { value = value && value[key]; });
  return (typeof value != 'undefined' && value !== null);
};

Working example on jsfiddle.

like image 55
dharcourt Avatar answered Jan 13 '23 12:01

dharcourt