Search code examples
javascriptcoding-styleconditional-statements

Better way for checking nested object in `if` condition?


Consider I have a object like this:

Obj.Boo.Foo.Zoo

Ok now if I want to be sure that zoo has a value and not empty, I should do:

if(Obj != null && Obj.Boo != null && Obj.Boo.Foo != null && Obj.Boo.Foo.Zoo != null) {
    //blah blah
}

And If I have more nested objects after Zoo, I should expand the if and the code becomes a little bit malformed.

Is there any better way for doing that type of conditions?


Solution

  • I keep a little function I call chainGet(obj, chain, default) around for situations just like this:

    function chainGet(obj, chain, dflt) {
        if (typeof chain === "string")
            chain = chain.split(".");
        var result = obj;
        for (var i = 0; i < chain.length; i += 1) {
            if (result === undefined)
                break;
            result = result[chain[i]];
        }
        return result === undefined? dflt : result;
    }
    

    For example:

    > chainGet({ foo: 42 }, "foo")
    42
    > chainGet({ foo: 42 }, "bar", "x")
    'x'
    > chainGet({ foo: { bar: 42 }}), "foo.bar")
    42
    

    This even works with arrays:

    > chainGet([{ foo: [42] }], [0, "foo", 0])
    42
    

    Of course, long chains of dotted accesses are a code smell, so caution should be exercised when using them… but sometimes you've just got to do it ;)