The problem with something like the desired approach:

if (option.name == "Option1") {

is that 'name' is a valid key, so if you had an object like

{'name':'john'}

option.name would equal 'john' (same problem if you tried option.key).

Also, though your example only has one key, an object can have mutiple
keys.

Easiest way is just loop through the keys (fast since there's only one
key/value pair in your object):

$.each(JSON.options, function(i, option) {
       for(k in option) {
            if(k === 'Option1'){
              // do something
            }
       }
});



On Oct 16, 5:41 pm, Frederic Laruelle <frederic.larue...@gmail.com>
wrote:
> Hi,
>
> I;m looking for a way to obtain key names from a JSON object:
> eg
> "options": [
>                 {"Option1" : ["Value1", "Value2"]},
>                 {"Option2" : ["Value3", "Value4"]},
>                 {"Option3" : ["Value5", "Value6"]}
>                 ]
>
> so, i'd like to consume this JSON in a way similar to this:
> $.each(JSON.options., function(i, option) {
>         if (option.name == "Option1") {
>                        // do something
>                        }
>
> });
>
> Prototype seems to have a keys method which would achieve what i'm
> looking for.
> There are also a few pages which attempt to address the issue with
> JQuery, such as:http://snipplr.com/view/10430/jquery-object-keys/
> However i was only able to retrieve the numerical index of the array
> elements using these methods (vs their name).
>
> Any help appreciated.
>
> Tks!
>
> Fred~

Reply via email to