Created
November 24, 2020 14:04
-
-
Save smitroshin/2a12fadac4b56e2d02b84143d9ee30c6 to your computer and use it in GitHub Desktop.
Get value from object by path
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
/** | |
* 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