Javascript ignore-if-null statement?

In javascript, I have many such codes.

if (ctrl && ctrl.main && ctrl.main.user) {
    SetTheme(ctrl.main.user.theme);
}

which is annoyingly long. In other languages, you can simply

SetTheme(ctrl?.main?.user?.theme);

Is there any way to do this in javascript?

I tried,

function safeGet(a,b) { return a ? a[b] : null; }

and

SetTheme(safeGet(safeGet(safeGet(ctrl, 'main'), 'user'), 'theme'));

But this is not very readable.

+4
source share
2 answers

The right short cut may be

if (((ctrl || {}).main || {}).user) { // ...

Or you can use the array as a path or a dot-separated string as a path and check for existence and return a 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"));
Run codeHide result
+1
source

You can create a general function for this by passing it a string representing the path to the attached property:

  function getValue(object, prop, /*optional*/ valIfUndefined) {
            var propsArray = prop.split(".");
            while(propsArray.length > 0) {
                var currentProp = propsArray.shift();
                if (object.hasOwnProperty(currentProp)) {
                    object = object[currentProp];
                } else {
                    if (valIfUndefined) {
                        return valIfUndefined;
                    } else {
                        return undefined;
                    }
                }
            }

            return object;
        }

Then use this on any object, for example:

// This will return null if any object in the path doesn't exist
if (getValue(ctrl, 'main.user', null)) {
    // do something
}
+1

Source: https://habr.com/ru/post/1663139/


All Articles