Skip to content

Instantly share code, notes, and snippets.

@smitroshin
Created November 24, 2020 14:04
Show Gist options
  • Save smitroshin/2a12fadac4b56e2d02b84143d9ee30c6 to your computer and use it in GitHub Desktop.
Save smitroshin/2a12fadac4b56e2d02b84143d9ee30c6 to your computer and use it in GitHub Desktop.
Get value from object by path
/**
* Get value from object by path (ex. parent.child.id)
* Source: https://stackoverflow.com/questions/8817394/javascript-get-deep-value-from-object-by-passing-path-to-it-as-string
*
* @param {object} obj
* @param {string} path
* @returns {undefined|*}
*/
const deepFind = (obj, path) => {
const paths = path.split('.');
let current = obj;
for (let i = 0; i < paths.length; ++i) {
if (!current[paths[i]]) {
return undefined;
} else {
current = current[paths[i]];
}
}
return current;
};
export default deepFind;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment