Skip to content

Instantly share code, notes, and snippets.

@todgru
Created May 21, 2020 22:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save todgru/37b11b51bc2a1ba4cf316dfd2d51d1a4 to your computer and use it in GitHub Desktop.
Save todgru/37b11b51bc2a1ba4cf316dfd2d51d1a4 to your computer and use it in GitHub Desktop.
vanilla javascript version of lodash get
/**
* The behaves the same as the lodash version https://www.npmjs.com/package/lodash.get
*
* Source: https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_get
*/
const get = (obj, path, defaultValue = undefined) => {
const travel = regexp =>
String.prototype.split
.call(path, regexp)
.filter(Boolean)
.reduce((res, key) => (res !== null && res !== undefined ? res[key] : res), obj);
const result = travel(/[,[\]]+?/) || travel(/[,[\].]+?/);
return result === undefined || result === obj ? defaultValue : result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment