1

I'm using this code

data?.response[0]?.Transaction[0]?.UID;

here Transaction key is not available, i'm getting

ERROR TypeError: Cannot read properties of undefined (reading '0')

I was trying to check for null or undefined using Optional Chaining rather than checking it with if.

user3653474
  • 3,393
  • 6
  • 49
  • 135

1 Answers1

1

Optional chaining works for array indexes too:

data?.response?.[0]?.Transaction?.[0]?.UID

For example:

const obj = {
  arr: [1]
};

console.log('exists:', obj?.arr?.[0]);
console.log('does not exist:', obj?.another_arr?.[0]);
David
  • 208,112
  • 36
  • 198
  • 279