I'm trying to create a multi-level dropdown using Bootstrap and some JSON data.
Ideally, I want the dropdown to have this kind of nested functionality:
I'm working with an array of objects with nested data, and it looks like:
[
{
ID: 1,
Title: "Middle Earth",
Locations: [
{
Category: "Lothlorien",
Child: [
{
PersonTitle: "Galadriel",
Link: "https://www.galadriel.lot"
},
{
PersonTitle: "Celeborn",
Link: "https://www.celeb.lot"
}
]
},
{
Category: "Mordor",
Child: [
{
PersonTitle: "Saruman",
Link: "https://www.srmn.org"
}
]
}
]
},
{
ID: 2,
Title: "Arrakis",
Locations: [...]
}
]
Questions:
- Can I create the submenu functionality with a template literal, and perform the mapping from there? (see code below)
- Or do I have to create separate
$.each
orforEach
blocks for every layer of the dropdown? For instance, "For every region (Middle Earth, Arrakis, etc) create 1 layer of the dropdown. Then for every Location within that region, create a submenu. Then for every PersonTitle within that Location, create..." etc.
I've worked with arrays of objects before, but not with this level of complexity, nor have I created submenu dropdowns with data.
Here's a code sample:
console.log("regions", regionsData);
if (regionsData.length > 0) {
$.each(regionsData, (index, item) => {
const csContainer = $(".mo_cs-dropdown");
const dropdownGroup = `
<div class="submenu-item">
<a class="dropdown-item dropdown-toggle dropright" data-region="${item.Title}" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">${item.Title}</a>
<div class="dropdown-menu">
<li class="dropdown dropend">
<ul class="dropdown-menu aria-labelledby="dropdownMenuLink">
<li class="dropdown dropend">
${Object.keys(
item.Locations.map(key => {
return `<a class='dropdown-item dropdown-toggle dropright' href='#' role='button' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>${item.Locations.Child}</a>`;
})
)}
<ul class="dropdown menu" aria-labelledby="">
<li><a class="dropdown-item" href="#">test item</a></li>
</ul>
</li>
</ul>
</li>
</div>
</div>`;
csContainer.append(dropdownGroup);
});
} else {
...
}
Here's a screencap of console.log(regionsData)
w/ redacted info: https://i.stack.imgur.com/HQEXo.png