JQuery $ .each () not working on object as expected

I have the following object:

var objectVar = { 4 : { "key" : "key-name4", "item4" : {} }, 3 : { "key" : "key-name3", "item3" : {} } } 

Then I will try the following:

 $(objectVar).each(function(index,record){ console.log(record); // Loops Only Once and Logs Full Object }); 

Can someone help me why $ .each (); does a function iterate through auxiliary objects in the main object?

Any help would be appreciated!

+4
source share
5 answers

"Can someone help me why the function $ .each (); iterates through helper objects in the main object?"

To loop auxiliary objects, you will need subperiods.

When using the each() [docs] method, as you usually usually work (as it is now) , this is really intended for DOM elements.

Use jQuery.each() [docs] method jQuery.each() :

 $.each( objectVar, function(index,record){ console.log(record); // start a loop on the current record in the iteration $.each( record, function( index2, sub_record ) { console.log( index2, sub_record ); }); }); 

Now your cycle will be expanded to the first level of nested objects.

If you are not sure about the overall structure and want to list the entire depth, you will need to check each value found to see if it should be listed.

+9
source
 $.each(objectVar,function(index,record){ console.log(record); }); 
+3
source

You must use $. each instead . :

 $.each(objectVar, function(index, record) { console.log(record); }); 
+3
source

While jQuery is great, you really don't use it. Passing JavaScript through objects is pretty simple:

 var record; for(var key in objectVar) { record = objectVar[key]; } 
+2
source

You are using $.each() incorrectly for objects other than jQuery:

 $.each( objectVar, function( index, record ){ console.log( record ); }); 

jQuery.each ()

+1
source

All Articles