0

I have the following object self.originalData on the console:

enter image description here

However, when I try to access to first object in the array of originalData,

self.originalData[0hcMSJXljH]

getting the following error

the Uncaught>Syntax Error: Unexpected token ILLEGAL

I could not able to figure out where I am doing wrong.

casillas
  • 16,351
  • 19
  • 115
  • 215
  • 3
    Enclose the index in quotes if you're directly accessing it. – meder omuraliev May 12 '15 at 19:43
  • 1
    Very closely related, but coming at it from the other side: [Dynamically access object property using variable](http://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – apsillers May 12 '15 at 19:47

5 Answers5

3

You can use:

self.originalData["0hcMSJXljH"]

instead. Object keys are strings so if you use the [] notation, then you have to put a string or a variable that contains a string inside the brackets.

Your particular case is a bit unusual because usually, you can use the dot notation as in obj.property, but because your key starts with a number, it is not a legal identifier to use with the dot notation (you can't do self.originalData.0hcMSJXljH). So, you are forced to use the bracket notation with that particular key.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
2

Try putting the key in quotes like this:

self.originalData['0hcMSJXljH']
mnickell
  • 66
  • 3
1

Have you tried

self.originalData["0hcMSJXljH"];

?

Otherwise:

self.originalData.0hcMSJXljH;

EDIT: last one not possible because the first char is a number, as explained to me

moonknight
  • 334
  • 1
  • 7
1

You must use quotes:

self.originalData['0hcMSJXljH']
marsh
  • 1,431
  • 1
  • 13
  • 19
1

You don't use quotes in your key, so it seems you are trying to use the variable identified by 0hcMSJXljH as the key. However, 0hcMSJXljH isn't a valid variable identifier, because it begins with a number, so your get an illegal-character error.

Simply use a string, not an identifier:

self.originalData["0hcMSJXljH"]
apsillers
  • 112,806
  • 17
  • 235
  • 239