Reputation: 67
I am working on a project where I am getting the JSON output below and want to create a menu from it. Group having parent and child menu using JavaScript:
myArray = [
{group: "one", color: "red"},
{group: "two", color: "blue"},
{group: "one", color: "green"},
{group: "one", color: "black"}
]
I want the output below in html
One
red
green
black
Two
blue
<ul class="nested">one
<li><a href=“red”>red</li>
<li><a href=“green”>green</li>
<li><a href=“black”>black</li>
</ul>
<ul class="nested">two
<li><a href=“blue”>blue</li>
</ul>
Upvotes: 2
Views: 197
Reputation: 3286
The first step here is going to be keying the array by the group
property. I would do something like this:
let keyedMenu = {};
myArray.forEach((item) => {
if (!keyedMenu[item.group]) {
keyedMenu[item.group] = [];
}
keyedMenu[item.group].push(item);
});
Now you have your data in a structure that looks like this:
{
one: [
{ group: 'one', color: 'red' },
{ group: 'one', color: 'green' },
{ group: 'one', color: 'black' }
],
two: [
{ group: 'two', color: 'blue' }
]
}
The next step is creating the markup from this data structure:
let markup = ``;
Object.keys(keyedMenu).forEach((key) => {
markup += `<ul class="nested">${ key }`;
keyedMenu[key].forEach((item) => {
markup += `<li><a href="${ item.color }">${ item.color }</a></li>`;
});
markup += `</ul>`;
});
Finally, you'll want to inject this markup into the DOM:
$('target-element-selector').html(markup);
Upvotes: 2