Skip to content

Instantly share code, notes, and snippets.

@pi0
Forked from harish2704/lodash.get.js
Last active February 1, 2018 23:30
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 pi0/a077066f62d129e1ec75c9e3f1406e61 to your computer and use it in GitHub Desktop.
Save pi0/a077066f62d129e1ec75c9e3f1406e61 to your computer and use it in GitHub Desktop.
Simple lodash.get function in javascript
/**
* getProp - Simple lodash.get implementation
* @author @harish2704, @muffypl, @pi0
* @param {Object} object
* @param {String|Array} path
* @param {*} defaultVal
*/
function getProp (object, path, defaultVal) {
const _path = Array.isArray(path)
? path
: path.split('.').filter(i => i.length)
for (let key of _path) {
object = object[key]
if (object === undefined || object === null) {
return defaultVal
}
}
return object === undefined ? defaultVal : object
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment