image
The JSON data
Here’s the sample JSON data. It has a list of birds with ID, Name and Type. Distinct bird types will serve as "menus" and the names will form the "sub-menus".
By the way, you can even do this using plain old JavaScript. Check this article.
The Markup
In the <body> section, I have defined a <ul> tag, which is the parent ul element. The Lis and subsequent Uls and Lis will be created dynamically in the below script.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<ul id="menu1"></ul>
</body>
</html>
The jQuery Script
<script> $(document).ready(function () { // Top (header) list item. let li = $('<li/>').appendTo('#menu1'); $('<a />') .text('Birds') .attr('href', '#') .appendTo(li); // add the header (<ul>). // Create sub ul. let sub_ul = $('<ul/>').appendTo(li); let arrData = []; $.getJSON('../../library/birds.json', function (data) { let typeOfBirds = []; $.each(data, function (index, value) { typeOfBirds.push(value.Type); arrData = data; }); // Remove duplicates from the array, because we want unique types. typeOfBirds = Array.from(new Set (typeOfBirds)); $.each(typeOfBirds, function (index, value) { // Create and add sub list items. let sub_li = $('<li/>').appendTo(sub_ul); $('<a />') .text(value + ' + ') .attr('href', '#') .appendTo(sub_li); $.each(arrData, function (i, v) { if (v.Type === value) { // Create sub ul. let sub_sub_ul = $('<ul/>').appendTo(sub_li); let sub_sub_li = $('<li/>').appendTo(sub_sub_ul); $('<a />') .text(v.Name) .attr('href', '#') .appendTo(sub_sub_li); } }); }); }); }); </script>
After creating the top <li> tag (Birds) and appending it to the parent <ul> element, I am extracting JSON from a url using $.getJSON() method, for the remaining <ul> and <li> tags.
You may also like… How to create Cascading SELECT dropdown using JSON data and jQuery