0

I have a standard AJAX request:

$.ajax({
  type: "POST",
  contentType: "application/json;",
  ...,
  success: function(data){

    // Wanna loop the resultList here...

  }
});

...which returns a JSON object which looks like this:

{
   "notification": "Search complete",
   "resultList": [
      {
         "id": 1,
         "comment": "lorem"
      },
      {
         "id": 2,
         "comment": "ipsim"
      },
      {
         "id": 3,
         "comment": "dolor"
      }
   ]
}

How do I loop though this with jQuery so that the following is printed in the log:
ID #1 - lorem
ID #2 - ipsum
ID #3 - dolor

Sorry for posting another one of these but I can't figure out how to print this without including the notification. Hopefully this will help others as well..

2 Answers 2

2

Pretty simple, you have an array of objects:

for (var i = 0; i < data.resultList.length; i++) {
    console.log(data.resultList[i].id);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I was stuck thinking I should use .each but this works perfectly.
For reference (to get exactly what I asked for), it should be something like: console.log('ID #' + data.resultList[i].id + ' - ' + data.resultList[i].comment);
0

Since you asked for jQuery answer, here's one just for fun:

$.each(foo.resultList, function(i, item) {
    console.log('ID #' + item.id + ' - ' + item.comment);
});

1 Comment

Changing this to the accepted answer since I do prefer jQuery in this case.

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.