<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?
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.
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.
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.
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.
$.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); }); });
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>
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