It is notoriously annoying to get a deeper property from an object. If the parent does not exist, you get an error. So you need to stop getting to the property when a parent doe
Instead of try..catch, just test for the property:
function getProp(path, parent) {
path = path.split('.');
for (var k=0, kLen=path.length; k<kLen; k++) {
if (parent.hasOwnProperty(path[k])) {
parent = parent[path[k]];
} else {
return; // undefined? null? error?
}
}
return parent;
}
var obj = {a: {b: {c: 'C', d:'D'}}};
console.log(
getProp('a.b.d', obj) // D
);
Builtin ways, no. If you're in Node.js platform you can try some package like dotty.
Anyway, the way I think you could do it is somewhat like this (I haven't tested it! But I think it could work):
key.split( "." ).reduce(function( memo, part ) {
if ( typeof memo !== "object" || memo[ part ] === undefined ) {
return;
}
return memo[ part ];
}, obj );