I got this code to generate a nested list using jQuery:
HTML and JavaScript
jQuery(document).ready(function () {
var data = [
{ "id": "88", "name": "test", "parent_id": "0" },
{ "id": "8805", "name": "dsdsdsdsdsd", "parent_id": "88" },
{ "id": "8801", "name": "balloons", "parent_id": "88" },
{ "id": "8802", "name": "Other", "parent_id": "88" },
{ "id": "8804", "name": "Parac", "parent_id": "88" },
{ "id": "8803", "name": "Parts 11.02.", "parent_id": "88" },
{ "id": "880100", "name": "(2007-) airs", "parent_id": "8801" },
{ "id": "880110", "name": "(-2006) Glis", "parent_id": "8801" },
{ "id": "880190", "name": "(-2006) Other", "parent_id": "8801" }
];
var endMenu = getMenu("0");
function getMenu(parentId) {
return data.filter(function (node) { return (node.parent_id === parentId); }).sort(function (a, b) { return a.index > b.index }).map(function (node) {
var exists = data.some(function (childNode) { return childNode.parent_id === node.id; });
//console.log("exists is now " + exists);
var subMenu = (exists) ? '<ul>' + getMenu(node.id).join('') + '</ul>' : "";
//console.log("node name is now " + subMenu);
return '<li><a href="#">' + node.name + subMenu + '</a></li>';
});
}
$('.menu').html('<ul class="products">' + endMenu.join('') + '</ul>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu"></div>
The issue I am having is that the code generates a few empty a tag elements as follows:
<ul><a href="#"></a><li>
I have tried to step through the code but cant figure out where the issue is.