Last active
January 3, 2016 15:18
-
-
Save dobladez/8481514 to your computer and use it in GitHub Desktop.
In JavaScript: access deep object properties avoiding NPE checks
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
/** | |
* Provide a cleaner way to access deep object properties avoiding null pointers | |
* | |
* So, instead of doing this: | |
* | |
* var x = (obj && obj.prop && obj.prop[subprop] && obj.prop[subprop][lastprop]) || "default"; | |
* | |
* you can do: | |
* | |
* var x = get(obj, "prop", "subprop", subprop, lastprop) || "default"; | |
* | |
*/ | |
var deepGet = function (obj) { | |
if (obj === undefined || obj === null || arguments.length === 1) | |
return obj; | |
// convert arguments to a real Array | |
var args = [].slice.apply(arguments); | |
var newObj = obj[args[1]]; | |
var newArgs = args.slice(2); | |
newArgs.unshift(newObj); | |
return get.apply( this, newArgs ); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment