Last active
February 19, 2019 14:28
-
-
Save chrisgfortes/d9a03f878b747e671decb6d6646d4370 to your computer and use it in GitHub Desktop.
Pure _.get from lodash
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
function _stringToPath(path) { | |
const containsBracketNotation = /\[[0-9]+\]/g; | |
if (path.match(containsBracketNotation)) { | |
path = path.replace(containsBracketNotation, s => `.${s.substring(1, s.length - 1)}`); | |
} | |
return path.split('.'); | |
} | |
function get(source, path, defaultArgument) { | |
return _stringToPath(path).reduce((nestedObject, key) => { | |
return nestedObject && key in nestedObject ? nestedObject[key] : void 0; | |
}, source) || defaultArgument; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment