You could just check every value and keep checking until you run out of depth. I have written a little helper function below that will automate this process:
function checkDeep(object){
for(var i = 1; i < arguments.length; i++){
if(typeof object[arguments[i]] !== "undefined"){
/* Check the type of the nested value - if not undefined,
* set it to `object` and continue looping. */
object = object[arguments[i]]
} else {
/* If it is not undefined, return false. */
return false;
}
}
/* If we made it past the loop, all the values exist and we return true. */
return true;
}
You can add as many variables to this as you like at the end and see if they are nested within the previous value. If it hits a break in the chain anywhere, it will return false. So its definition would be:
checkDeep(object, var1[, var2, var3, ...]);
It would be called as such:
checkDeep({a:{b:{c:['d']}}}, 'a', 'b', 'c'); // true
checkDeep({a:{b:{c:['d']}}}, 'a', 'c', 'c'); // false
If you want the value at that position, just return object
at the end of the function instead of return true
.
function checkDeep(object){
for(var i = 1; i < arguments.length; i++){
if(typeof object[arguments[i]] != 'undefined') object = object[arguments[i]]
else return false;
}
return true;
}
var object = {a:{b:{c:['d']}}};
document.write("Order a,c,c in '{a:{b:{c:['d']}}}' is " + (checkDeep(object, 'a', 'c', 'c') ? "true" : "false") + "<br />");
checkDeep(object, 'a', 'c', 'c'); // false
document.write("Order a,b,c in '{a:{b:{c:['d']}}}' is " + (checkDeep(object, 'a', 'b', 'c') ? "true" : "false") + "<br />");
checkDeep(object, 'a', 'b', 'c'); // true