Created
July 13, 2018 14:50
-
-
Save Couto/ce9c5447ea8eb2afabb72589c22d42ea to your computer and use it in GitHub Desktop.
Lodash's .get() similar
This file contains hidden or 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
/** | |
* | |
* @param {any} defaultValue | |
* @param {String} propertyPath 'a.b.c.4' | |
* @param {any} obj | defaultValue | |
* @example getValue('foo', 'a.b.c.4', { a:{ b:{ c: [0, 1, 2, 3] } } }) // 3 | |
*/ | |
var getValue = exports.getValue = function (defaultValue, propertyPath, obj) { | |
var paths = propertyPath.split('.'); | |
var currentObj = obj; | |
if (!obj) { return defaultValue; } | |
return paths.reduce(function(acc, key) { | |
var currentValue = currentObj[key]; | |
if (currentValue === undefined || currentValue === null) { | |
return defaultValue; | |
} | |
if (typeof currentValue === 'object') { | |
currentObj = currentObj[key]; | |
return currentValue; | |
} | |
return currentValue; | |
}, defaultValue); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment