user495208
user495208

Reputation: 345

jquery each with json object

i have this json response:

[{
    "i": 39,
    "id": "15399"
},
{
    "i": 38,
    "id": "15386"
},
{
    "i": 37,
    "id": "15329"
}]

now i need to put these elements in a html list. how can i use $.each to do that?

(something like:


  • 39: 15399
  • 38: 15386
  • etc...)

    (btw. i have no access to the file that generates the json code)

    Upvotes: 1

    Views: 5037

    Answers (2)

    tobyodavies
    tobyodavies

    Reputation: 28099

    No need, it is just a javascript array - you can just use a for loop...

    for(var idx=0;idx<JSONResponse.length;idx++){
        var elem=JSONResponse[idx];
        $('ul#somewhere').append('<li>'+elem.i+': '+elem.id+'</li>');
    }
    

    Upvotes: 0

    Nick Craver
    Nick Craver

    Reputation: 630379

    Just iterate over your array, for example:

    var list = $("#myList");
    $.each(data, function(i, obj) {
      $("<li />", { text: obj.i + ": " + obj.id }).appendTo(list);
    });
    

    In a $.each() callback, you get the index and the object as parameters, in this case you just want to use the i and id properties off that. The alternative is just a ordinary for loop, like this:

    var list = $("#myList");
    for(var i=0, l=data.length; i<l; i++) {
      var obj = data[i];
      $("<li />", { text: obj.i + ": " + obj.id }).appendTo(list);
    });
    

    Upvotes: 3

    Related Questions