Skip to content

Instantly share code, notes, and snippets.

@evanrmurphy
Last active December 28, 2015 10:39
Show Gist options
  • Save evanrmurphy/7488169 to your computer and use it in GitHub Desktop.
Save evanrmurphy/7488169 to your computer and use it in GitHub Desktop.
var obj = {a: {b: 1}};
getIf(obj, 'a'); // => {b: 1}
getIf(obj, 'absentProp'); // => undefined
getIf(obj, 'a', 'b'); // => 1
getIf(obj, 'a', 'b', 'absentNestedProp'); // => undefined
// Get nested property of an object without risking
// "TypeError: Cannot read property '[...]' of undefined"
// errors. Depends on Lo-Dash or Underscore.
function getIf(maybeObj) {
var props = _.rest(arguments);
return getIf1(maybeObj, props);
}
// Helper function that does the heavy lifting for `getIf`
function getIf1(maybeObj, props) {
if (_.isEmpty(props)) return maybeObj;
if (!_.isObject(maybeObj)) return undefined;
return getIf1(maybeObj[_.first(props)], _.rest(props));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment