Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery $.each() for objects

Tags:

jquery

each

<script>     $(document).ready(function() {         var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };         $.each(data.programs[0], function(key,val) {             alert(key+val);         });     }); </script> 

This code retrieves the first data. name:zonealarm and price:500.

How can I retrieve all the data in the object?

I tried $.each(data.programs, function(key,val) but it didn't work.

Should I put it in a loop?

like image 851
matiasdelgado Avatar asked Jun 01 '11 21:06

matiasdelgado


People also ask

How do you iterate through an object in jQuery?

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.

What is the use of each () function in jQuery?

each() jQuery's each() function is used to loop through each element of the target jQuery object — an object that contains one or more DOM elements, and exposes all jQuery functions. It's very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties.

Can we use foreach in jQuery?

each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.

How do I get out of each loop in jQuery?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.


2 Answers

$.each() works for objects and arrays both:

var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };  $.each(data.programs, function (i) {     $.each(data.programs[i], function (key, val) {         alert(key + val);     }); }); 

...and since you will get the current array element as second argument:

$.each(data.programs, function (i, currProgram) {     $.each(currProgram, function (key, val) {         alert(key + val);     }); }); 
like image 93
Tomalak Avatar answered Nov 12 '22 06:11

Tomalak


You are indeed passing the first data item to the each function.

Pass data.programs to the each function instead. Change the code to as below:

<script>          $(document).ready(function() {                  var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };                  $.each(data.programs, function(key,val) {                          alert(key+val);                  });          });  </script>  
like image 21
Chandu Avatar answered Nov 12 '22 06:11

Chandu