JavaScript - Get Nested Property
// http://stackoverflow.com/questions/23808928/javascript-elegant-way-to-check-nested-object-properties-for-null-undefined
get = function(obj, key) {
return key.split(".").reduce(function(o, x) {
return (typeof o == "undefined" || o === null) ? o : o[x];
}, obj);
}
// Usage:
get(user, 'loc.lat') // 50
get(user, 'loc.foo.bar') // undefined
// Or, to check only if a property exists, without getting its value:
has = function(obj, key) {
return typeof get(obj, key) !== 'undefined';
}
// Usage:
if(has(user, 'loc.lat')) {
// something
}