JQuery looping on json array

I get the following JSON string from a web service.

[{"TITLE":"asdasdasd","DESCRIPTION":"asdasd","PORTFOLIOID":1},
 {"TITLE":"sss","DESCRIPTION":"sss","PORTFOLIOID":2},
 {"TITLE":"sdfsdf","DESCRIPTION":"sdfsfsdf","PORTFOLIOID":3}]

Is it possible to iterate over this array in jquery and output individual key / value pairs?

0
source share
2 answers

That's right. Assuming you tell jQuery to evaluate this response as JSON using AJAX methods, you simply do the following:

<script>
$(data).each(function(idx, obj) //this loops the array
{
    $(obj).each(function(key, value) //this loops the attributes of the object
    {
        console.log(key + ": " + value);
    }
}
</script>
+1
source
var a = [{"TITLE":"asdasdasd","DESCRIPTION":"asdasd","PORTFOLIOID":1}, ....]

$(a).each(function(index)
{
   //this is the object in the array, index is the index of the object in the array
   alert(this.TITLE + ' ' this.DESCRIPTION)
});

Check out jQuery docs for more info ... http://api.jquery.com/jQuery.each/

+2
source

All Articles