tags:

views:

47

answers:

3

Possible Duplicate:
javascript test for existence of nested object key

Consider this:

typeof(object.prop1.prop2) == "undefined"

where object.prop1 is undefined

This will output a javascript error, how to handle this situation beautifully?
ie: no multiple if

A: 

Wrap inside a try/catch block if you don't want to repeat your if conditions, only way I can think of;

try {
    var x = object.prop1.prop2.prop3.prop4;
} catch(e) {
    console.log("Not enough levels.");
}

Edit,

I don't find this very pretty though... If you could explain your data structure a bit more, maybe one could provide a definitive answer. Are you looking for a property far down the structure? A time ago I wrote some kind of XPath for PHP arrays-function, and it is probably applicable on javascript objects/arrays as well. An attempt for objects (and it works what I can tell):

<html>
<head>
<body>
<script>
window.onload = function() {
    function isObject(o) {
        return (typeof o == 'object' && typeof o.length == 'undefined');
    }

    function object_xpath(object, path) {
        var nodes = path.split('/');
        return object_xpath_helper(object, nodes);
    }

    function object_xpath_helper(object, nodes) {
        if (isObject(object) && nodes.length > 0) {
            var node = nodes.shift();

            if (nodes.length > 0 && isObject(object[node]))
                return object_xpath_helper(object[node], nodes);
            else if (nodes.length == 0)
                return object[node];
        }

        return false;
    }

    var testObject = {
        'one': {
            'two': 'just a string!',
            'three': {
                'four': 'mhmm.',
                'five': {
                    'findMe': 'Here I am!'
                }
            }
        }
    };

    console.log(object_xpath(testObject, 'one/three/five/findMe'));
    console.log(object_xpath(testObject, 'one/three/four/foobar'));

    /* And you should be able to use it in conditional statements as well: */
    if (object_xpath(testObject, 'one/two/nine'))
        console.log("This should never be printed");
    if (object_xpath(testObject, 'one/two'))
        console.log("Found it!");
}
</script>
</body>
</html>
Björn
A: 

@Björn's answer is probably the simplest way to do it, but there may be times when you need more information; in which case, you'll just have to test incrementally; eg:

if(foo && foo.bar != undefined && foo.bar.baz != undefined ...)
mway
A: 
if(typeof(object.prop1) == "undefined" ? false : (typeof(object.prop1.prop2) == "undefined" ? false : true)) {
  //isnt this beautifull?
}
Mark Baijens