Created
May 21, 2020 22:01
-
-
Save todgru/37b11b51bc2a1ba4cf316dfd2d51d1a4 to your computer and use it in GitHub Desktop.
vanilla javascript version of lodash get
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
/** | |
* 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