Skip to content

Instantly share code, notes, and snippets.

@Anoesj
Last active April 30, 2020 21:29
Show Gist options
  • Save Anoesj/65b64463b38d75c9ed85dadb9ed366e4 to your computer and use it in GitHub Desktop.
Save Anoesj/65b64463b38d75c9ed85dadb9ed366e4 to your computer and use it in GitHub Desktop.
Get value by object path
// 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);
}
// 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