In javascript I have a lot of code like this.
if (ctrl && ctrl.main && ctrl.main.user) {
SetTheme(ctrl.main.user.theme);
}
which is annoyingly long. In other, languages you can do simply
SetTheme(ctrl?.main?.user?.theme);
Is there any way to do that in javascript?
I tried,
function safeGet(a,b) { return a ? a[b] : null; }
and
SetTheme(safeGet(safeGet(safeGet(ctrl, 'main'), 'user'), 'theme'));
But that's not very readable.
The correct short cut could be
if (((ctrl || {}).main || {}).user) { // ...
Or you could use an array as path, or a dot separated string as path and check aginst existence and return the value.
function getValue(object, path) {
return path.split('.').reduce(function (o, k) {
return (o || {})[k];
}, object);
}
var ctrl = { main: { user: { theme: 42 } } };
console.log(getValue(ctrl, "main.user.theme"));