This is a very simple nested property extractor. I wonder if it can be optimised further?
/**
* Extract nested property from object. If nested property cannot be reached, return value of rescue
* @param obj Object
* @param path Can be dot-separated string or array
* @param rescue (optional) default value. Defaults to null
*/
function extract(obj, path, rescue){
if (typeof obj === "object" && path){
var elements = typeof path === "string" ? path.split(".") : path;
if (typeof elements.shift === "function"){
var head = elements.shift();
if (obj.hasOwnProperty(head)){
return (elements.length === 0) ? obj[head] : extract(obj[head], elements, rescue);
} // if
} // if
} // if
return rescue || null;
} // extract
var noob = {k1 : {k11 : {k111 : "v1"}}, k2 : { k21 : "v2"}};
console.log(extract(noob, 'k1.k11')); // {k111 : "v1"}
console.log(extract(noob, 'k1.k11.k111')); // v1
console.log(extract(noob, ['k1', 'k11', 'k111'])); // v1
console.log(extract(noob, 'k1.k11.kx')); // null
console.log(extract(noob, 'k2')); // k2 : { k21 : "v2"}
console.log(extract(noob, 'k2.k21.k22')); // null
console.log(extract(noob, 'k1.k11.k22', "ZUT")); // ZUT
console.log(extract(noob, '', "ZUT")); // ZUT
console.log(extract(false, '', "ZUT")); // ZUT