Skip to content

Instantly share code, notes, and snippets.

@dovydasvenckus
Last active January 28, 2016 11:43
Show Gist options
  • Save dovydasvenckus/dd52698555bddda2c087 to your computer and use it in GitHub Desktop.
Save dovydasvenckus/dd52698555bddda2c087 to your computer and use it in GitHub Desktop.
Function that safely navigates javascript object. Original source http://adripofjavascript.com/blog/drips/making-deep-property-access-safe-in-javascript.html
//If not found returns undefined
function deepGet (obj, properties) {
// If we have reached an undefined/null property
// then stop executing and return undefined.
if (obj === undefined || obj === null) {
return;
}
// If the path array has no more elements, we've reached
// the intended property and return its value.
if (properties.length === 0) {
return obj;
}
// Prepare our found property and path array for recursion
var foundSoFar = obj[properties[0]];
var remainingProperties = properties.slice(1);
return deepGet(foundSoFar, remainingProperties);
}
//If not found or value is null or undefined returns specified default value
function deepGet (obj, props, defaultValue) {
// If we have reached an undefined/null property
// then stop executing and return the default value.
// If no default was provided it will be undefined.
if (obj === undefined || obj === null) {
return defaultValue;
}
// If the path array has no more elements, we've reached
// the intended property and return its value
if (props.length === 0) {
return obj;
}
// Prepare our found property and path array for recursion
var foundSoFar = obj[props[0]];
var remainingProps = props.slice(1);
return deepGet(foundSoFar, remainingProps, defaultValue);
}
var rels = {
Viola: {
Orsino: {
Olivia: {
Cesario: null
}
}
}
};
sallyRel = deepGet(rels, ["Viola", "Harry", "Sally"], {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment