0

How can I use the below syntax for nested object key if my object keys have spaces ?

var level3 = (((test || {}).level1 || {}).level2 || {}).level3;
alert( level3 );

So above works, but say if level1 key is actually "level 1", how can I get the above syntax to work ?

copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • 3
    `var level3 = (((test || {})["level 1"] || {}).level2 || {}).level3;` – Ricky Mo Sep 24 '21 at 07:32
  • [https://stackoverflow.com/questions/8317982/how-can-i-access-a-javascript-object-which-has-spaces-in-the-objects-key](https://stackoverflow.com/questions/8317982/how-can-i-access-a-javascript-object-which-has-spaces-in-the-objects-key) – Ricky Mo Sep 24 '21 at 07:37
  • `level3 = test?.["level 1"]?.["level 2"]?.["level 3"]` – ibrahim tanyalcin Sep 24 '21 at 07:54
  • @RickyMo - Thank you...that seems to work.... – copenndthagen Sep 24 '21 at 09:10
  • @ibrahimtanyalcin - I think this is the optional chaining syntax...While this would work, the only concern is cross-browser support (even though I don't need to support IE, but other modern ones) – copenndthagen Sep 24 '21 at 09:15

0 Answers0