dSquared
dSquared

Reputation: 9825

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" : {} }
}

I then try the following:

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

Can anyone help me with why the $.each(); function inst iterating through the sub objects within the main object?

Any help would be appreciated!

Upvotes: 10

Views: 29789

Answers (5)

user113716
user113716

Reputation: 322492

"Can anyone help me with why the $.each(); function inst iterating through the sub objects within the main object?"

To loop the sub objects, you need sub loops.

While using the each()[docs] method like you have will usually sometimes work (as it currently is), it is really meant for DOM elements.

Instead use the jQuery.each()[docs] method:

$.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 looping will be extended to the first level of nested objects.

If you're not sure of the overall structure, and want to enumerate the entire depth, you'll need to test each value encountered to see if it should be enumerated.

Upvotes: 16

Joe
Joe

Reputation: 82594

While jQuery is great, you really aren't using it. JavaScript looping through objects is fairly simple as is:

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

Upvotes: 3

dgilland
dgilland

Reputation: 2748

You're using $.each() incorrectly for non-jQuery objects:

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

jQuery.each()

Upvotes: 3

Guffa
Guffa

Reputation: 700272

You should use the $.each method instead of the .each method:

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

Upvotes: 5

DrStrangeLove
DrStrangeLove

Reputation: 11557

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

});

Upvotes: 3

Related Questions