Morgan Cheng Morgan Cheng - 2 months ago 13
Javascript Question

What's the simplest approach to check existence of deeply-nested object property in JavaScript?

I have to check deeply-nested object property such as YAHOO.Foo.Bar.xyz.

The code I'm currently using is

if (YAHOO && YAHOO.Foo && YAHOO.Foo.Bar && YAHOO.Foo.Bar.xyz) {
// operate on YAHOO.Foo.Bar.xyz
}


This works, but looks clumsy.

Is there any better way to check such deeply nested property?

Answer

Sometimes it's just easiest to just put a try catch around it and not worry about all the intermediate segments:

try {
    if (YAHOO.Foo.Bar.xyz) {
        // operate on YAHOO.Foo.Bar.xyz
} catch(e) {}

or, depending upon how your code works, it might even just be this:

try {
    // operate on YAHOO.Foo.Bar.xyz
} catch(e) {
    // do whatever you want to do when YAHOO.Foo.Bar.xyz doesn't exist
}

In general, javascript developers under-use try/catch. I find that I can often replace 5-10 if statements with a single try/catch around a larger function block and make the code a lot simpler and more readable at the same time. Obviously, when this is appropriate depends upon the particular code, but it's definitely worth considering more often than it usually is.

FYI, if the usual operation is to not throw an exception with the try/catch, it can be a lot faster than a bunch of if statements too.


If you don't want to use the exception handler, you can create a function to test any arbitrary path for you:

function checkPath(base, path) {
    var current = base;
    var components = path.split(".");
    for (var i = 0; i < components.length; i++) {
        if ((typeof current !== "object") || (!current.hasOwnProperty(components[i]))) {
            return false;
        }
        current = current[components[i]];
    }
    return true;
}

Example usage:

var a = {b: {c: {d: 5}}};
if (checkPath(a, "b.c.d")) {
    // a.b.c.d exists and can be safely accessed
}
Comments