Javascript JSON gets the name of an object principal

This may be a very simple question, but it seems not easy to find the answer. I have Json more or less 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 are several language objects inside language variables. and each language object has its own name as its identifier ("aa", "ab", "af")

So my question is: how to get these identifiers ("aa", "ab", "af") if I want to list all these languages ​​in html? eg. if I want to create as 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 to php syntax above for my json in java script?

ps. if you're wondering why I'm not using an array - I just think it will be easier to capture a specific language object (they just need to do something like: languages["af"] to get the Afrikaans language) and not do: the whole object language and check one by one if id is what I want and then return it. - you can give me another suggestion for this if you have a better idea :)

Best wishes,

and

+7
json javascript jquery html
source share
5 answers

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 http://www.jsfiddle.net/EsJAh/

+6
source share

You can use "for"

 for (var key in languages) { alert(key); } 
+3
source share
 var data = new Array(); for(var lang in languages) { data[lang] = languages[lang]; } 
+2
source share

Have you tried:

 languages['af'].labels.language_names[0] 

He will return Afrikaans

+2
source share

If you use jquery , you can actually do this:

 $.each( languages, function(k, v){ alert( "Key: " + k + ", Value: " + v ); // value is your particular language object based on k variable }); 

:)

0
source share

All Articles