Skip to content

Instantly share code, notes, and snippets.

@alexbruno
Last active April 27, 2021 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexbruno/840f69cea8475534072cc29ede646f63 to your computer and use it in GitHub Desktop.
Save alexbruno/840f69cea8475534072cc29ede646f63 to your computer and use it in GitHub Desktop.
Simple JS lodash.get like function
/**
* Simple JS lodash.get like function
*
* @export Function
* @param {*} object
* @param {String|Array} path
* @param {*} value
*/
export default function get(obj, path, value) {
const split = (key) =>
key
.toString()
.split('.')
.filter((k) => k)
const keys = Array.isArray(path) ? path.flatMap(split) : split(path)
const reduce = (obj, key) => obj && obj[key]
return keys.reduce(reduce, obj) || value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment