JQuery loop through JSON array

I have a json array that I select with ajax call and would like to skip it. The array displays the category category and some data records in this category. The array is as follows:

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

A basic function like me cannot help me.

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

I want to be able to display it with the title of the main category and below it that display the data.

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 result):

  • Beautiful title 1

Any help would be greatly appreciated. Thank.

+4
source share
4 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>
Run codeHide result
+8
source

Try

$.each(data, function(key, value) {
  $("<ul />", {
    "class": key.toLowerCase(),
    "html": key + " (" + value.length + " results)<br />"
  }).append($.map(value, function(title, i) {
    return $("<li />", {
      "html": Object.keys(title)[0] + ":" + title.title
    })[0].outerHTML
  })).appendTo("body");
});

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) {
  $("<ul />", {
    "class": key.toLowerCase(),
    "html": key + " (" + value.length + " results)<br />"
  }).append($.map(value, function(title, i) {
    return $("<li />", {
      "html": Object.keys(title)[0] + ":" + title.title
    })[0].outerHTML
  })).appendTo("body");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Run codeHide result
+1

.each(), .

$.each(data,function(i,object){
    console.log(i +'('+object.length+')')
    $.each(object, function (index, obj) {
        console.log(obj.title);
    });
});

Fiddle

+1

Travel

, :

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

All Articles