1

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)

    2 Answers 2

    3

    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);
    });
    
    Sign up to request clarification or add additional context in comments.

    9 Comments

    i have the json response in a variable called result, that means i should replace 'data' with 'result'?
    @user495208 - yup that's it :)
    you need to parse the json with var responseObj = $.parseJSON(responseObj) first then iterate over the object
    @Hersheezy - jQuery does this already if the response is JSON, assuming you either specify json, use $.getJSON(), or the headers are set correctly...I'd hope one of those is true :)
    @craver: correct. you only need to parse it if you use $.get() or $.post() without specifying. I usually use $.getJSON() or $.postJSON()
    |
    0

    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>');
    }
    

    1 Comment

    You should not use a for...in loop to iterate over an array, it's for enumerating an object.

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.