0

I have a following JSON representation:

var collectionCopy = JSON.parse(JSON.stringify(
 {
   1 : {
        2: "2"
   }  
}
));

Why cant I access key "2" using dot notation (i.e. collectionCopy.1.2) ?

2 Answers2

1

You can use the dot notation for accessing an object's properties only on a valid identifiers in the language.

And since numbers (or anything that starts with a number) are not a valid identifiers you can access it (as a property of an object) only with the bracket notation.

Jumpa
  • 878
  • 1
  • 8
  • 12
0

This is because the keys are strings not actual numbers:

to access it use:

collectionCopy[1][2]

or

collectionCopy['1']['2']

Relevant docs on accessing properties

omarjmh
  • 13,632
  • 6
  • 34
  • 42
  • but when i have a regular object `var newObject = {1:{2:"2"}};`, i can use dot notation `newObject.1.2`. Is this because i have `.stringify()`? Or JSON turns every key and value of key to string anyway? Thank you for docs, ill read them. – Dmytro Murzenkov Apr 09 '16 at 21:10
  • can you show me where that works? I just tried it and I cannot get it to work: https://jsbin.com/tevebi/1/edit?js,console – omarjmh Apr 09 '16 at 22:02
  • I assumed that it should work :D I think i just messed with simple syntax. `newObject.1.2` doesn't work and it shouldn't. But if I had object like this one `var newObject = {one:{two:"2"}}` `console.log(newObject.one.two)` prints `"2"` to console. – Dmytro Murzenkov Apr 10 '16 at 09:49