Skip to content

Instantly share code, notes, and snippets.

@chrisgfortes
Last active February 19, 2019 14:28
Show Gist options
  • Save chrisgfortes/d9a03f878b747e671decb6d6646d4370 to your computer and use it in GitHub Desktop.
Save chrisgfortes/d9a03f878b747e671decb6d6646d4370 to your computer and use it in GitHub Desktop.
Pure _.get from lodash
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