5

I have a large json object. I need to access x = a.b.c.d.e.f.g. However b (or c, d, e...) can be undefined. This data structure is being imported from somewhere else.

Is there a way to try to get to assign x with null or undefined without throwing an error?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Alexis
  • 23,545
  • 19
  • 104
  • 143
  • 1
    There is a proposal at stage 1 (there is a Babel plugin, though) https://github.com/tc39/proposal-optional-chaining | Also, duplicate: [Null-safe property access (and conditional assignment) in ES6/2015](https://stackoverflow.com/questions/32139078/null-safe-property-access-and-conditional-assignment-in-es6-2015/41897688) – yuriy636 Aug 31 '17 at 20:18

2 Answers2

7

Update

Optional chaining is now part of the ECMAScript spec and can be used on most javascript clients (browsers, node.js, etc)

x = a.b?.c?.d?.e?.f?.g

To use a default value if the access fails you can use the Nullish coalescing operator (??)

x = a.b?.c?.d?.e?.f?.g ?? 'my default value'

original answer (2017)

The easiest way is to use try catch

try {
  x = a.b.c.d.e.f.g
} catch(e) {
  x = undefined;
}

There is a proposal for this called optional chaining you can check it here: https://github.com/tc39/proposal-optional-chaining

x = a.b?.c?.d?.e?.f?.g

If you are using a transpiler you'll be able to use it, however its still in the very early stages and might not be accepted to be supported in the spec

Bamieh
  • 10,358
  • 4
  • 31
  • 52
4

There are some proposals to solve this ( syntactic sugar missing) problem. Hopefully somewhen we may do this:

let x = a?.b?.c?.d?.e;

However, until then we need to fall back to objects if the variable is undefined:

var x =( ( ( ( (a || {}).b || {} ) || {} ).c || {} ).d || {}).e;

I admit that this is quite ugly. Maybe object destructuring is more beautiful:

let ({ 
   b: { 
     c: { 
       d: { e:x } = {}
     } = {}
   } = {}
}) = a;
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151