1

When you have an object with multiple nested properties and you must "navigate" its interiors to reach what you want to get, like:

var innerProperty = obj[level1][level2][level3];

maybe you will get undefined when reaching level 2, so the next level, undefined[level3], will halt your code with an error.

The correct way is to check if every level exists before attempting to reach the next one, but code will start to become clumsy:

if (obj[level1] && obj[level1][level2]) {
    var innerProperty = obj[level1][level2][level3];
}

Then, again, you must check if innerProperty is undefined.

What is the best way to deal with this, keeping the code clean and not needing to repeat the nested level names inside each if clause you use?

Eduardo Poço
  • 2,819
  • 1
  • 19
  • 27
  • 1
    There is currently a proposal out for what you're asking for called optional chaining in Javascript: https://github.com/tc39/proposal-optional-chaining. It unfortunately has not been implemented yet in most browsers though /: – Nicholas Siegmundt Feb 14 '20 at 17:31
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining - quite new feature, you probably need to use babel. – ASDFGerte Feb 14 '20 at 17:31
  • 2
    Does this answer your question? [Test for existence of nested JavaScript object key](https://stackoverflow.com/questions/2631001/test-for-existence-of-nested-javascript-object-key) – ASDFGerte Feb 14 '20 at 17:32
  • Wow, exactly what I wanted... even the structure of the question is similar, thanks! Too bad I couldn't find it before asking again. – Eduardo Poço Feb 14 '20 at 17:37

0 Answers0