aanders77
aanders77

Reputation: 630

Why does parseJSON wrap my JavaScript object in a new object?

Consider this JavaScript object wrapped as JSON:

vars = $.parseJSON('{"timestamp":1402720347,"AktiveSprak":{"en":{"ID":"en","Norsk_navn":"Engelsk","Lokalt_navn":"English","Bilde":"flagg_en.png","Aktivt":"1"},"no":{"ID":"no","Norsk_navn":"Norsk","Lokalt_navn":"Norsk","Bilde":"flagg_no.png","Aktivt":"1"}}}')

I want to iterate over the object AktiveSprak, but I can’t figure out how.

Now I can do vars.AktiveSprak but in order to use jQuery's .each function the object needs to be wrapped in jQuery like this $(vars). Now, why can't I do any of these:

$(vars).AktiveSprak.each(function(){})
$(vars)[0].AktiveSprak.each(function(){})
$(vars).find("AktiveSprak").each(function(){})
$(vars)[0].find("AktiveSprak").each(function(){})

Upvotes: 1

Views: 80

Answers (2)

rplantiko
rplantiko

Reputation: 2738

Even when using jQuery, not every iteration must be performed with $.each. In this case, better use JavaScript's built-in in iterator

var s = $.parseJSON('{"timestamp":..., "AktiveSprak":{ "de":..., "no":... }}');
for (var lang in s.AktiveSprak) { 
  console.log( lang ); 
  }

Upvotes: 1

Exlord
Exlord

Reputation: 5371

$(object).each can only be called on jquery objects to use with normal objects :

$.each(vars.AktiveSprak,function(index,item){});

http://api.jquery.com/jquery.each/

The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array.

Upvotes: 6

Related Questions