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?
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.
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 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.
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).
I think you're looking for jQuery.each() instead of .each()
try this:
$.each(myassoc, function(index, value){
//your code
});
try this:
$.each(assocarray,function(i, value){
console.log('index: ' + i + ',value: ' + value);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With