最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check for 'undefined' anywhere in object chain? - Stack Overflow

programmeradmin0浏览0评论

I would like to check if any object is missing in plex object chain. I've e up with following solution, is there a better way acplish 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');

I would like to check if any object is missing in plex object chain. I've e up with following solution, is there a better way acplish 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');
Share Improve this question asked Jul 27, 2012 at 14:24 krulkrul 2,2794 gold badges30 silver badges52 bronze badges 3
  • 1 possible duplicate of javascript test for existence of nested object key – Felix Kling Commented Jul 27, 2012 at 14:32
  • @Felix The question is not a duplicate. The duplicate does not account for inherit properties from the prototype chain. – Rob W Commented Jul 27, 2012 at 14:51
  • @RobW: This was not asked for and is easy to change. The overall approach does not change. – Felix Kling Commented Jul 27, 2012 at 15:14
Add a ment  | 

3 Answers 3

Reset to default 7

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.

Your concept is OK, but the code has to be changed. When a property has the null value, it can't have any properties. Trying to access a property on null results in an error. To fix this, use:

for (var i=0; i<props.length; i++) {
    var prp = props[i],
        val = topObj[prp];
    lg('checking property: ' + prp); 
    if (typeof val === 'undefined') {
        lg(prp + ' undefined!');
        return false;
    } else if (val === null) {
        return i === props.length-1; // True if last, false otherwise
    } else {
        topObj = val;
    }
}

Keep it simple as you learned once in the theory. Try/catch the exception thrown within a custom function.

let obj1 = {
    x: {
        y: 10
    }
};

export function def(chain){
    try{
        let lookup = eval(chain);
        return true;
    } catch (e){
        return false;
    }
}

//true
document.write(def('obj1.x.y'));
//false (at any moment in the given chain)
document.write(def('obj1.k.v'));
发布评论

评论列表(0)

  1. 暂无评论