Last active
April 30, 2020 21:29
-
-
Save Anoesj/65b64463b38d75c9ed85dadb9ed366e4 to your computer and use it in GitHub Desktop.
Get value by object path
This file contains 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 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