Skip to content

Instantly share code, notes, and snippets.

@Couto
Created July 13, 2018 14:50
Show Gist options
  • Save Couto/ce9c5447ea8eb2afabb72589c22d42ea to your computer and use it in GitHub Desktop.
Save Couto/ce9c5447ea8eb2afabb72589c22d42ea to your computer and use it in GitHub Desktop.
Lodash's .get() similar
/**
*
* @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