Skip to content

Instantly share code, notes, and snippets.

@nash403
Last active September 14, 2016 08:28
Show Gist options
  • Save nash403/e117698b5bd6abec2d77241386abdae1 to your computer and use it in GitHub Desktop.
Save nash403/e117698b5bd6abec2d77241386abdae1 to your computer and use it in GitHub Desktop.
Safe access to any nested value of a javascript object without getting a TypeError but undefined instead.
// Utils
function isFnCall(key){
if (typeof key !== 'string') return false;
return key.slice(-2) === "()";
}
/*
* @param {key} string concatenation of nested keys in this form: 'foo.bar.toto'.
* You can even call a function if the last key ends with '()'.
* @param {obj} the object we are accessing
* @return a nested value OR the result of a nested function OR undefined
*/
export default function safe_get(key, obj) {
let splitted = key.split('.');
let lastkey = splitted.pop();
isFnCallLastkey = isFnCall(lastkey);
lastkey = isFnCallLastkey ? lastkey.slice(0,-2) : lastkey;
let beforelast = splitted.reduce((a,b) => {
return a && a[b];
}, obj);
return beforelast && (typeof beforelast === 'object') && (isFnCallLastkey ? beforelast[lastkey]() : beforelast[lastkey]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment