find-value
Version:
Find object values by passing the path as string.
34 lines (28 loc) • 762 B
JavaScript
/**
* findValue
* Finds the value at given path in the specified object.
* @name findValue
* @function
* @param {object} obj The input object.
* @param {string} path The path to the value you want to find.
* @returns {Anything} The path value.
*/
export default function findValue(obj, path) {
const dotIndex = path.indexOf(".");
if (!~dotIndex) {
if (obj === undefined || obj === null) {
return undefined;
}
return obj[path];
}
const field = path.substring(0, dotIndex);
const rest = path.substring(dotIndex + 1);
if (obj === undefined || obj === null) {
return undefined;
}
obj = obj[field];
if (!rest) {
return obj;
}
return findValue(obj, rest);
};