0

I am having an issue understanding why Optional Chaining does not work in my code here. I am sure it is my code that is broken, but I would like to learn what the appropriate way to handle this is. In an ideal world, I can do this:

let traitType = trait['trait_type'];
let traitValue = trait['value'];    
let configTrait = overrideBids.traitType?.traitValue;

Both traitType and traitValue are of type String objects. I get a syntax error with the example above. Instead, what does work is this more verbose code:

  let configTrait = null;
  if (overrideBids[trait['trait_type']]) {
      configTrait = overrideBids[trait['trait_type']][trait['value']];
  }
      

Is there a cleaner way using Optional Chaining or some other modern JavaScript solution to replace the condition I have above to something less verbose?

randombits
  • 47,058
  • 76
  • 251
  • 433
  • When you use dot notation, the property name is literal, not a variable. – Barmar Aug 03 '21 at 01:13
  • @Barmar thank you, so is the way I have it the least verbose way of going forward with a solution? – randombits Aug 03 '21 at 01:15
  • Does this answer your question? [Using optional chaining operator for object property access](https://stackoverflow.com/questions/58780817/using-optional-chaining-operator-for-object-property-access) – Heretic Monkey Aug 03 '21 at 01:20

1 Answers1

1

To use a variable property name with optional chaining, you have to use square brackets, just like normal dynamic property access.

let configTrait = overrideBids[traitType]?.[traitValue];
Barmar
  • 741,623
  • 53
  • 500
  • 612