null checking of array using question mark break

Viewed 1366

I have this array of object

const a = {a:[{b:[{prop: 10}]}]}

to access the value of 10 I do

a.a[0].b[0].prop // 10

I use this fallback, make sure things doesn't break but it didn't work?

a?.a[0]?.b[0]?.prop

, I can use something like lodash's get or check using the old method but how to use the question mark syntax?

3 Answers

Optional chaining should be written as below

a?.[0]?.b?.[0].prop

This should be foolproof:

const a = {
  a: [{
    b: [{
      prop: 10
    }]
  }]
};

console.log(a?.a?.[0]?.b?.[0]?.prop);

This should work

a?.a?.[0]?.b?.[0]?.prop

Alternatively, you could use || operator to get to the desired value.

(((a || {}).a || [{}])[0].b || [{}])[0].prop

Related