Check if object member exists in nested object

Is there a simpler way than using ___ in object to check the existence of each level of an object to check the existence of a single member?

More concisely: How can I check if someObject.member.member.member.value exists?


In general, you can use if(property in object), but this would be still cumbersome for nested members.

You could write a function:

function test(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];
        }
        else {
            return false;
        }
    }
    return true;
}

test(someObject, 'member.member.member.value');

DEMO


You could also try/catch TypeError?

try {
  console.log(someObject.member.member.member.value);
} catch(e) {
  if (e instanceof TypeError) {
    console.log("Couldn't access someObject.member.member.member.value");
    console.log(someObject);
  }
}

Here's one way: http://jsfiddle.net/9McHq/

var result = ((((someObject || {}).member || {}).member || {}).member || {}).value;

alert( result );