Last active
December 28, 2015 10:39
-
-
Save evanrmurphy/7488169 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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