casillas
casillas

Reputation: 16813

Accessing Javascript Object with Key

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.

Upvotes: 0

Views: 60

Answers (5)

marsh
marsh

Reputation: 1441

You must use quotes:

self.originalData['0hcMSJXljH']

Upvotes: 1

moonknight
moonknight

Reputation: 334

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

Upvotes: 1

jfriend00
jfriend00

Reputation: 708116

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.

Upvotes: 3

apsillers
apsillers

Reputation: 116030

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"]

Upvotes: 1

mnickell
mnickell

Reputation: 66

Try putting the key in quotes like this:

self.originalData['0hcMSJXljH']

Upvotes: 2

Related Questions