Javascript JsON get object member name
this is might be a very basic question, but seems like it's not easy to find the answer. I have a Json, more or less is like:
languages = {
"aa":{"iso639-2T":"aar","family":"Afro-Asiatic","labels":{"language_names":["Afar"],"native_names":["Afaraf"]}},
"ab":{"iso639-2T":"abk","family":"Northwest Caucasian","labels":{"language_names":["Abkhaz"],"native_names":["\u0430\u04a7\u0441\u0443\u0430"]}},
"af":{"iso639-2T":"afr","family":"Indo-European","labels":{"language_names":["Afrikaans"],"native_names":["Afrikaans"]}}, etc...etc... }
if you see json above, there's several language object inside languages variable. and each language object has its own name as its identifier ("aa", "ab", "af")
so then, my question is, how to get those identifier ("aa", "ab", "af") if i want to list all of those language in html? eg. if i want to create like a combo box (<option value="aa">Afar</option><option value="ab">Abkhaz</option><option value="af">Afrikaans</option>
)
actually what i want to achieve is something like this (in php)
$sampleArray = Array("aa" => "Afar", "ab" => "Abkhaz", "af" => "Afrikaans"); foreach($sampleArray as $id => $value){ /* I can get the id from $id* / }
is there any solution similar like php syntax above for my json in java script?
ps. if you're wondering why i'm not using array - I'm just thinking it will easier to grab certain language object (im just do something like: languages["af"]
to get afrikaans language) rather than i should do: loop through the entire language object and check one-by-one if the id is what i want, and then retur开发者_开发技巧n it. - you can give me another suggestion for this if you guys have a better idea :)
Best Regards,
AnD
this should do what you want..
to see them
for (var lang in languages)
alert(lang + ' : ' + languages[lang].labels.language_names[0]);
to put them in the DOM
var $select = $('selector to your select element');
for (var lang in languages)
$select.append('<option value="'+lang+'">' + languages[lang].labels.language_names[0] + '</option>');
Working code at http://www.jsfiddle.net/EsJAh/
You can use the "for"
for (var key in languages)
{
alert(key);
}
Did you try:
languages['af'].labels.language_names[0]
It will return Afrikaans
var data = new Array();
for(var lang in languages) {
data[lang] = languages[lang];
}
If you're using jquery, then you can do this actually:
$.each( languages, function(k, v){
alert( "Key: " + k + ", Value: " + v );
// value is your particular language object based on k variable
});
:)
精彩评论