Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json keys as numbers

I have a JSON passed to script. I do not know JSON keys as they are dynamic.

Actually, they are numbers. That's what I'm getting.

var countries = {"223":"142,143","222":"23,26,25,24","170":"1,2"};

I tried to access data like this:

var objKey = 223;  (var objKey = "223";)
countries.objKey;

I tried changing JSON to

var countries = {"country223":"142,143","country222":"23,26,25,24","country170":"1,2"};

... and access it like this:

var objKey = "country"+223; (var objKey = "country"+"223";)
countries.objKey;

... again nothing.

Any advice would be greatly appreciated.

like image 650
Jeffz Avatar asked Feb 09 '11 19:02

Jeffz


1 Answers

Instead of this:

countries.objKey;

Do this:

 countries[objKey];

With square bracket notation, you can use the value referenced in a variable (or use a string or number) to reference the property name.

like image 93
user113716 Avatar answered Oct 27 '22 00:10

user113716