10

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.

Jeffz
  • 2,075
  • 5
  • 36
  • 51

1 Answers1

35

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.

user113716
  • 318,772
  • 63
  • 451
  • 440
  • 1
    @patrick dw I'm still at the very beginning of my JS adventure :) – Jeffz Feb 09 '11 at 19:38
  • ...so JSON and JS objects look same to me. If you look at them, they are constructed pretty much same. – Jeffz Feb 09 '11 at 19:40
  • @Jeffz: I removed that part of the comment because I wasn't sure what you meant by *"JSON passed to script"*. Thought perhaps it had started off as JSON. Basically, JSON data is a text based data interchange format. It just happens to look like javascript objects and arrays because that's what the standard is based on. But it really isn't JSON unless it is just text. For example, this is an object literal `{"a":"b"}`, but this is valid JSON `'{"a":"b"}'` (notice the outer quotes), which can be parsed into the first object. – user113716 Feb 09 '11 at 19:43
  • @patrick dw - thank you again for your note, it is definitely helpful, I just hope, that it will be rather sooner than later, when I stop asking "silly" qs :)) .. but that is how you learn ... have a good one .. thanks .. Jeff – Jeffz Feb 09 '11 at 19:48
  • @Jeffz: Not silly at all. Indeed that is how you learn. You have a good one too. :o) – user113716 Feb 09 '11 at 19:50