Skip to content

Instantly share code, notes, and snippets.

@floscr
Created July 18, 2016 08:42
Show Gist options
  • Save floscr/32896db7cd8812898a5badd0bf871746 to your computer and use it in GitHub Desktop.
Save floscr/32896db7cd8812898a5badd0bf871746 to your computer and use it in GitHub Desktop.
Deep Get an Object
// http://adripofjavascript.com/blog/drips/making-deep-property-access-safe-in-javascript.html
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);
}
sallyRel = deepGet(rels, ["Viola", "Harry", "Sally"], {});
// Will output a graph based on the empty object
graph(sallyRel);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment