-
-
Save pi0/a077066f62d129e1ec75c9e3f1406e61 to your computer and use it in GitHub Desktop.
Simple lodash.get function in javascript
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
/** | |
* 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