2

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>
1
  • Stack Overflow is not a free code writing service. You are expected to try to write the code yourself. After doing more research if you have a problem you can post what you've tried with a clear explanation of what isn't working and providing a minimal reproducible example. I suggest reading How to Ask a good question. Also, be sure to take the tour Commented Sep 30, 2019 at 22:14

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your quick responses. I am not good at JavaScript. Pls can u put all the code today, for me to understand it at my level? Assuming I want to render it in <div Id=“mymenu><\div>
I'm not sure what more you are asking for... but the code I have included in my answer will get you what you want.
Thanks for your help. Will try it and get back to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.