-
-
Save sardor01/0594cf3ad4625bafc8d9a7fe5e1ec36c to your computer and use it in GitHub Desktop.
Get value by object 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
| // LONG VERSION WITH ERROR LOGGING | |
| function getValueByObjectPath (obj, path) { | |
| const pathSplit = path.split('.'); | |
| return pathSplit.reduce((value, pathPart, depth) => { | |
| try { | |
| return value[pathPart]; | |
| } | |
| catch (err) { | |
| let pathSoFar = ''; | |
| for (let i = 0; i < depth; i++) { | |
| pathSoFar += pathSplit[i]; | |
| if (i !== depth - 1) pathSoFar += '.'; | |
| } | |
| console.warn(`Failed to get property '${pathPart}' at ${pathSoFar} in object:`, obj); | |
| throw err; | |
| } | |
| }, obj); | |
| } |
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
| // SHORT VERSION WITHOUT ERROR LOGGING | |
| function getValueByObjectPath (obj, path) { | |
| return path.split('.').reduce((value, pathPart) => { | |
| try { | |
| return value[pathPart]; | |
| } | |
| catch (err) { | |
| throw err; | |
| } | |
| }, obj); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment