Well, now you can do that without all the question marks:
var access = require('safe-access'); access(very, 'nested.property.and.array.func()');
obj.that.is.very.nested will throw an error if the property
var nestedThang = obj.that && obj.that.is && obj.that.is.very && obj.that.is.very.nested;
nestedThang will simply be
that doesn't exist (instead of throwing an error). But, this gets quite messy (and annoying to type out).
The equivalent, using
var access = require('safe-access'); var nestedThang = access(obj, 'that.is.very.nested');
safe-access can even be used to safely access arrays and call functions:
var obscenelyNested = access(obj, 'leading.to.array.andFunc()');
var obscenelyNested = obj && obj.leading && obj.leading.to && obj.leading.to.array && obj.leading.to.array && obj.leading.to.array.andFunc && (typeof obj.leading.to.array.andFunc === 'function' ? obj.leading.to.array.andFunc() : undefined);
Sometimes, it's necessary to call functions with some arguments. Every argument after the accessor string (3rd argument and beyond) will be used as the arguments to each function call in the accessor string. Like this:
// equivalent of `obj.thing.add(1, 2);` access(obj, 'thing.add()', [1, 2]);
Or maybe you have multiple function calls that receive arguments:
// equivalent of `thing.add(1, 2).toFixed(1).substr(2);` access(obj, 'thing.add().toFixed().substr()', [1, 2], 1, 2);
Notice that if you need to pass in multiple arguments (like in the
add function), you'll need to pass the arguments as an array. The caveat is if you need to pass in an array as an argument, you'll need to pass in a nested array.
An example, passing in an array as an argument:
access(window._, 'compact()', [[ false, 'boop', 'beep', '', 'meep' ]]); // returns [ 'boop', 'beep', 'meep' ] OR undefined if window._ doesn't exist
safe-access auto-curries, which means omitting the second argument will return a function that you can use to access the same object over and over again. This can be useful if you are accessing many different nested properties on an object.
var objDot = access(obj); objDot('nested.thing'); // obj.nested.thing objDot('other.nested.thing'); // obj.other.nested.thing