I have a multidimensional object array like this.
var categories = [{
text: "engine",
children: [1,2,3, {
text: "piston",
children: [4,5,6]
}]
}, {
text: "tire",
children: [7,8,9]
}];
Everytime the index of the categories array equals an array there must be a dropdown menu with the contents of the array in it and it can be endless. If the index of the array is not equal to an array it should just be an a tag.
I am trying to achieve something like this:
I have tried altering this code below to make it suit my needs I did this in combination with a self made dropdown menu in html and css, but at this point it does not make sense anymore.
function menuToElement(menu) {
const ul = document.createElement("ul");
for (const item of menu) {
const li = document.createElement("li");
if (Object(item) === item) {
li.textContent = item.text;
li.appendChild(menuToElement(item.children));
} else {
li.textContent = item;
}
ul.appendChild(li);
}
return ul;
}
const ul = menuToElement(categories);
document.getElementById("menu").appendChild(ul);
The result I was getting is that I was only able to show the names engine and tire, but couldn't get a dropdown with the children in it to work. What I want to ask is if someone can explain what the code above does exactly and whether I approach this in the right way.
This is how I tried making the dropdown menu it is not fully working anymore because I was trying to make it append using the other code.
<div class="popup" onclick="togglePopup2()">
<div class="sel popuptext" id="myPopup2">
<div class='txt'>Select</div>
<div id="Select" class="options hide">
<div>Option 1</div>
<div>Option 2</div>
<div>Option 3</div>
</div>
</div>
<img src="~/images/circle.png" class="category" id="1">
</div>
var txt = $('.txt'),
options = $('.options');
txt.click(function (e) {
e.stopPropagation();
var content = $(e.target).text();
console.log(content);
$('#'+ content).show();
});
$('body').click(function (e) {
options.hide();
});
}