user1788736 user1788736 -4 years ago 89
jQuery Question

How to display distinct json genre names (and total number of each genre type)?

I have JSON data structured like so...

{
"resp": [{
"genreID": 1,
"genre": "All TV Series",
"length": "3.5",
"name": "Passion",
"vid": 12345,

}, {
"genreID": 1,
"genre": "All TV Series",
"length": "1.9",
"name": "Galaxy",
"vid": 12346,


}, {
"genreID": 1,
"genre": "All TV Series",
"length": "1.4",
"name": "Sun",
"vid": 12347,


}, {
"genreID": 8,
"genre": "Thriller",
"length": "15.1",
"name": "Moonlight ",
"vid": 12348,


}, {
"genreID": 8,
"genre": "Thriller",
"length": "10.6",
"name": "Sunlight",
"vid": 12349,


}]
}


I would like to create following hyperlinks from above json data and once we click on each genre name hyperlink it should only display data from that genre only. Right now my code display the whole json in a list using the code below.

Want to create following hyperlinks:

All TV Series(3)
Thriller(2)


How would I accomplish this with Javascript/jQuery? Unfortunately I can't edit what the server is sending me.

code:

success: function(data) {

self.itemParts = data.resp;

for (var i = 0; i < self.itemParts.length; i++)
{


// create HTML code
var div = "<div class=\"image\">\n" +
"<a href=\"javascript:loadList('" + self.itemParts[i].vid+ "')\">\n" +
"<img src=\"http://somesite.com/images/l"+ self.itemParts[i].vid +".png\" alt=\"..\" />"+ self.itemParts[i].name+"\n" +
"</a>\n" +
"</div>\n";
// append it inside <body> tag.
$("#myDiv").append(div);

}


<div id='myDiv' style="display: visiable;">

</div>

Answer Source

Let's say that the returned data resides in a variable called data

let data = {
    "resp": [{
        "genreID": 1,
        "genre": "All TV Series",
        "length": "3.5",
        "name": "Passion",
        "vid": 12345,

    }, {
        "genreID": 1,
        "genre": "All TV Series",
        "length": "1.9",
        "name": "Galaxy",
        "vid": 12346,


    }, {
        "genreID": 1,
        "genre": "All TV Series",
        "length": "1.4",
        "name": "Sun",
        "vid": 12347,


    }, {
        "genreID": 8,
        "genre": "Thriller",
        "length": "15.1",
        "name": "Moonlight ",
        "vid": 12348,


    }, {
        "genreID": 8,
        "genre": "Thriller",
        "length": "10.6",
        "name": "Sunlight",
        "vid": 12349,


    }]
};

let model = {};
let values = data.resp;
values.forEach(function(value) {
  //creating separate groups for each type
  model[value.genre] = model[value.genre] || [];
  model[value.genre].push(value);
});

then do another iteration to generate the links:

es6

for(let genre in model) {
  $("#myDiv").append(`<a href="#">${genre}(${model[genre].length})</a>`); 
}

es5

for(let genre in model) {
  $("#myDiv").append('<a href="#">'+genre+'('+model[genre].length+')</a>'); 
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download