Pattern to avoid long dot-notation chains

I think you've got the two prettiest solutions already.

But note that for something like, say, obj.obj.string.length your first solution will fail if string === "". Since an empty string is falsey, it'll trip the && guard.

But speaking of strings, you could do something like:

function getNestedProperty(obj, propChain) {
    var props = propChain.slice(0), prop = props.shift();
    if(typeof obj[prop] !== "undefined") {
        if(props.length) {
            return getNestedProperty(obj[prop], props);
        } else {
            return obj[prop];
        }
    }
}

var v = getNestedProperty(a, ["b", "c", 0, "d", "e"]);

Yeah... not too pretty :P

I'd say that, of the solutions proposed, try...catch is probably the simplest way to go

Tags:

Javascript