0

If I have an object with a space in the property name:

var myObj = { prop1: 12, 'prop two': { abc: 123} };

What's the correct syntax to access 'prop two' (or e.g. a non-existent 'prop three') with optional chaining?

I've tried various combinations. The obvious one would be myObj['prop two']?['abc'] or myObj['prop two']?.['abc'] but neither work. I need to attempt access on a non-existent property and return undefined as dot notation would (but I can't use dot notation with spaces)

Thanks

Alex Kerr
  • 956
  • 15
  • 44
  • 1
    `myObj['prop two']?.['abc']` is exactly correct. I see no reason why it wouldn't work for you, unless the object is different. – VLAZ May 19 '22 at 13:13
  • 3
    [works fine](https://jsfiddle.net/Lrtswepq/) – trincot May 19 '22 at 13:16
  • @VLAZ Thanks, OK I see what's going on, I'm on a corporately controlled PC and using Chrome 76.0.3809.100 and actually it doesn't work on that and gives console error "Uncaught SyntaxError: Unexpected token ." but does work on Edge on the same PC for some reason. I will have to work around it... – Alex Kerr May 19 '22 at 14:12
  • @trincot not for me, as above, but you are correct so thanks – Alex Kerr May 19 '22 at 14:12
  • @AlexKerr optional chaining is not supported at all on Chrome 76: https://caniuse.com/mdn-javascript_operators_optional_chaining it's available starting Chrome 80. – VLAZ May 19 '22 at 14:14

0 Answers0