<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?
Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.
You have programs: [ {...}, {...} ] so programs[0] is { "name":"zonealarm", "price":"500" } So your loop is just going over that.
You could do an outer loop over the array
$.each(data.programs, function(index) {
// then loop over the object elements
$.each(data.programs[index], function(key, value) {
console.log(key + ": " + value);
}
}
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>
Source: Stackoverflow.com