Skip to content

Instantly share code, notes, and snippets.

@dobladez
Last active January 3, 2016 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dobladez/8481514 to your computer and use it in GitHub Desktop.
Save dobladez/8481514 to your computer and use it in GitHub Desktop.
In JavaScript: access deep object properties avoiding NPE checks
/**
* 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