0

So I've got an object containing multiple objects, like this:

let data = {
    hello: {
        melon: {
           yes: true
        }
    }
}

Here I want to check if "yes" is equal to true. The problem being that the "data" object could contain nothing, and the "hello" object could contain nothing, and it goes on. Here's what I did:

if(data.hello && && data.hello.melon && data.hello.melon.yes && data.hello.melon.yes === true){...}

Is there a way to make this condition cleaner?

Hell Protection
  • 323
  • 3
  • 5
  • 11
  • Consider [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). – zero298 May 28 '20 at 17:59
  • ---------- If you use ES6 there is [optional chaining][1] so you can do const isTrue = data?.hello?.melon?.yes This will return `undefined` which is translated to `false` in conditional statement. But if you really need `boolean` use double exclamation mark `!!` to convert it to `boolean`, so full code will look like const isTrue = !!data?.hello?.melon?.yes [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining – shark May 28 '20 at 18:06

1 Answers1

0

in ES2020 there is cool feature called optional chaining, so you can use it:

let foo = data?.hello?.melon?.yes

Also you can combine it with feature called nulish coalescing to set default value:

let foo = data?.hello?.melon?.yes ?? 'default value'

So the condition will look like:

if (data?.hello?.melon?.yes === true)

elvira.genkel
  • 1,303
  • 1
  • 4
  • 11