I have an multidimensional array categories and I am looping over this array with menuToElement function.
It takes al the elements of the array and its children and returns it in a ul. the code is fully working, but what I can't figure out is how to loop over only one element of the array and all its children.
What I want to do is for example only loop over the engine element and all its children and all the children arrays. My question is: Is this even possible with the for...of loop that I am using, because I tried looping over the index of categories and it says it is not iterable.
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 + ' \u25BD';
li.appendChild(menuToElement(item.children));
} else {
li.textContent = item;
}
ul.appendChild(li);
}
return ul;
}
var categories = [{
text: "engine",
children: [1, 2, 3, {
text: "piston",
children: [4, 5, 6, {
text: "piston",
children: [4, 5, 6]
}]
}]
}, {
text: "tire",
children: [7, 8, 9]
}];
const ul = menuToElement(categories);
document.getElementById("menu").appendChild(ul);
li>ul {
display: none;
}
li:hover>ul {
display: block;
}
<div id="menu"></div>