I have an array of objects whose schema is something like this.
[
{ text: 'Contents', level: 2 },
{ text: 'h2 Heading', level: 2 },
{ text: 'h3 Heading', level: 3 },
{ text: 'h4 Heading', level: 4 },
{ text: 'Heading', level: 2 },
]
I want to create an unordered list based on the levels of each object. So, for eg. the above array should be displayed as:
<ul>
<li>Contents</li>
<li>
h2 Heading
<ul>
<li>
h3 Heading
<ul>
<li>h4 Heading</li>
</ul>
</li>
</ul>
</li>
<li>Heading</li>
</ul>
I can check for the next object if it has the same level as the previous one. And handle the queries accordingly, but is there a better solution? Or any solution that works properly.
Edit #1: Just now, I found a solution that was asked here around 13 years ago. I can style the elements giving it a perception of a nested list. Link: Produce heading hierarchy as ordered list
Still, if there is a better solution, please do reply.