Skip to content

Instantly share code, notes, and snippets.

@todgru todgru/get.js
Created May 21, 2020

Embed
What would you like to do?
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
You can’t perform that action at this time.