Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery loop through JSON array

I have a json array which i fetch by a ajax call and would like to loop through it. The array outputs a category titel and some data records within that category. The array is as followed:

{"Travel":[{"title":"Beautiful title 1"},{"title":"Beautiful title 2"},{"title":"Beautiful title 3"}],"Other":[{"title":"Beautiful title 1"}]}

The basic each function like so can't help me.

$.each(data, function(key, value) {
    console.log(value.title);
}

I want to be able to output it with the main category title and under that have the data records shown.

So for example i want it to look like this:

Travel (3 results):

  • Beautiful title 1
  • Beautiful title 2
  • Beautiful title 3
  • List item

Other (1 results):

  • Beautiful title 1

Any help would be greatly appreciated. Thank you.

like image 727
Adriaan Avatar asked May 12 '15 04:05

Adriaan


1 Answers

var data = {"Travel":[{"title":"Beautiful title 1"},{"title":"Beautiful title 2"},{"title":"Beautiful title 3"}],"Other":[{"title":"Beautiful title 1"}]};

$.each(data, function (key, value) {
  $('body').append($('<div></div>').html(key + ' (' + value.length + ' results)'));
  var list = $('<ul></ul>');
  $('body').append(list);
  $.each(value, function (index, titleObj) {
    list.append('<li>' + titleObj.title + '</li>');
    
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
like image 109
Vigneswaran Marimuthu Avatar answered Oct 19 '22 23:10

Vigneswaran Marimuthu