Reputation: 625
I have JSON coming from the database that's shaped like this:
var data = {
"zone01": [{
"region": "North",
"state": "New York",
"county": "Albany",
"code": "01"
}, {
"region": "North",
"state": "New York",
"county": "Albany",
"code": "05"
}, {
"region": "North",
"state": "Maine",
"county": "Auburn",
"code": "07"
}],
"zone02": [{
"region": "South",
"state": "Florida",
"county": "Gainseville",
"code": "82"
}, {
"region": "South",
"state": "Florida",
"county": "Macclenny",
"code": "73"
}]
};
I'm trying to get a list of the first set of values "zone01", "zone02" etc... in order to populate a select input. By selecting the zone you'll be able to select down the list but I can't seem to get a list of the zones.
I tried:
$.each(data, function(index, element){
var zone = JSON.stringify(element.index);
$('#zone').append('<option value="'+zone+'">'+zone+'</option>');
});
but just get undefined. Here's the jsfiddle.
UPDATED FINISHED CODE
Here is my competed code: jsFiddle
Upvotes: 2
Views: 9815
Reputation: 44740
$.each(data, function(k,v){
var zone = k;
$('#zone').append('<option value="'+zone+'">'+zone+'</option>');
});
Upvotes: 4
Reputation: 151
I don't know how to do this with jQuery.each, but you can get the zone names like this:
for (var zone in data) {
$(#zone").append('<option value="'+zone+'">'+zone+'</option>');
}
Upvotes: 0
Reputation: 8610
I think you're really looking for the first set of indices(or indexes). You can probably remove the var zone
line, and just replace zone
with index
on the second loop line.
Also for future reference, if you have:
obj = { "akey": 5 };
index = "akey";
It seems like you tried to retrieve the value as "obj.index
". The way to retrieve the number 5 would be like this...
obj[index] // evalutes to 5
Upvotes: 1
Reputation: 115920
You simply need to use index
, not element.index
.
var zone = JSON.stringify(index);
element
refers to the value on the right side of the colon. It does not have an index
property.
index
refers to the identifier on the left side of the colon. This is exactly what you want.
Upvotes: 6