Checking JavaScript objects for existence of a nested element

A common pattern in modern AJAX-based websites is to receive a structured object as a response to an API call, and then take pieces of that object and insert them into the web page.

It's not unusual for the piece you want to be missing from the object received, and in any case it's just good programming practice to check that it's there before trying to use it. JavaScript as a language is more prone to throwing an error in these situations, and it's also harder to write the test, especially if the object has multiple levels.

For example, your object order might represent a sales order, and you're hoping to find the sales rep's name in The plain JS way of checking that while inserting it into the DOM would be something like this:

$('.rep_name', $order_details).text((typeof(order.branch) !== 'undefined') && (typeof(order.branch.rep) !== 'undefined') && (typeof( !== 'undefined') ? : '');

Yike — not only do you have to use the very ugly and verbose typeof(x) !== undefined to test for existence, you also have to do it at each and every level of the object!

Alternately, in isolated instances where there are many levels and I'm just interested in one property, I have been known to assume it's there but wrap it in a try … catch block just in case. Quick, but not exactly elegant.

I had the outline of a solution to this in my head, but I cribbed the code from a Stack Overflow article anyway — the first hit when I searched looked like exactly what I was thinking of, so it saved me some typing :)

 * Test if an object contains the specified property - handles multiple levels.
 * e.g object_has_property({'a' : {'b' : {'c' : 1'}}}, 'a.b.c') == true
function object_has_property(obj, prop)
    var parts = prop.split('.');
    for (var i = 0, l = parts.length; i < l; i++)
            var part = parts[i];
            if ((obj !== null) && (typeof(obj) === 'object') && (part in obj))
            obj = obj[part];
            return false;
    return true;

Here's the example above rewritten —much more concisely — with this function:

$('.rep_name', $order_details).text(object_has_property(order, '') ? : '');

Something to say?