keziah keziah - 6 months ago 16
HTML Question

jQuery JSON append ul according to the number of sets

I want jQuery to make new

ul
for each set of products.
Inside of each
ul
, all items of each set will be appended.
The result was unexpected; there should be only 2
ul
, but
11
ul
were appended.

My jQuery

$.getJSON('/products.json', function (result) {
var booksobj = result.ebooks.basic;

/* EBOOKS*/
$.each(booksobj.set, function(i, item) {
$('#ebook').append('<ul>'); // Append new list sets
$('#ebook ul').append('<li><a href="#" data-id="' + item.product_id + '" data-type="' + item.type + '">' + item.title + '</a></li>');
});
});


products.json

{
"ebooks": {
"basic": {
"set": [
{
"title": "PDF Sample",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample",
"product_id": 2,
"type": "ebook"
}, // ...
],
"set": [
{
"title": "PDF Sample",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample",
"product_id": 2,
"type": "ebook"
}, // ...
]
}
}
}


Thanks in advance.

Answer

You're looping over set and for each item inside a set, you're creating a new ul element. You need to have multiple loops where you create an ul and afterwards add all the lis for the section. I changed your data structure, you don't need the set properties (and they're overriding each other as property names are unique). basic is now an array which consists of arrays which represent a set.

var data = {
    "ebooks": {
        "basic": [
            [
                {
                    "title": "PDF Sample 1",
                    "product_id": 1,
                    "type": "ebook"
                },
                {
                    "title": "PDF Sample 2",
                    "product_id": 2,
                    "type": "ebook"
                },
            ],
            [
                {
                    "title": "PDF Sample 3",
                    "product_id": 1,
                    "type": "ebook"
                },
                {
                    "title": "PDF Sample 4",
                    "product_id": 2,
                    "type": "ebook"
                },
            ]
        ]
    }
}


data.ebooks.basic.forEach(function(set) {
    var $list = $('<ul></ul>');
  
    set.forEach(function(pdf) {
        $list.append('<li>' + pdf.title +  '</li>')
    });
              
    $('#ebook').append($list);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ebook"></div>