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>