Last active
September 14, 2016 08:28
-
-
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.
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
// 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