1

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(){})
1
  • 1
    Why are you trying to use $(vars) at all? Your vars is already a reference to the object, so you can say vars.AktiveSprak. Commented Jun 14, 2014 at 5:48

2 Answers 2

6

$(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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 ); 
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.