Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does jQuery.each() work with associative arrays (objects)?

I have an associative array with two object inside. Running this through $(myassoc).each(), the callback runs only once. Also the callback parameters (index and object) returns 0 and the entire associative array, respectively.

One would expect jQuery.each() to run for each element in the array, returning the correct keys as index and the correct element as the object.

Why isn't that happening, and can jQuery do what I'm after?

like image 351
Hubro Avatar asked Jun 08 '11 08:06

Hubro


People also ask

What is the use of jQuery each () function?

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. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How can you use array with jQuery?

Syntax And Declaration: var arr1=[]; var arr2=[1,2,3]; var arr2=["India","usa","uk"]; Type of Array: The type of an array is “object“. Iteration Approach: We use the length property of the array to iterate in the array. Iteration Approach using JQuery: jQuery provides a generic .

What is object as associative array in JavaScript?

What is an associative array? Associative arrays are basically objects in JavaScript where indexes are replaced by user-defined keys. They do not have a length property like a normal array and cannot be traversed using a normal for loop.

Can we use forEach loop in jQuery?

forEach() methods. There are also libraries like foreach which let you iterate over the key value pairs of either an array-like object or a dictionary-like object. Remember: $. each() and $(selector).


2 Answers

I think you're looking for jQuery.each() instead of .each()

try this:

    $.each(myassoc, function(index, value){
      //your code
    });
like image 58
dapangro Avatar answered Oct 22 '22 15:10

dapangro


try this:

$.each(assocarray,function(i, value){
  console.log('index: ' + i + ',value: ' + value);
});
like image 31
thecodeparadox Avatar answered Oct 22 '22 13:10

thecodeparadox