I have the following code below and trying to find a way to generate <ul>
and <li>
to output an unordered list via Javascript.
Question(s):
- How can I parse the following array to generate a nested unordered list html?
- If I were to use recursion, how would I recursively iterate through all nested children to print a nested unordered list?
What I tried that didn’t work
const data = [
{
name: '125313-7j',
},
{
name: '584996-s7',
_children: [
{
name: '747773-jw',
},
{
name: '377526-zg',
_children: [
{
name: '955330-wp',
},
{
name: '343693-9x',
},
],
},
{
name: '638483-y2'
},
],
},
{
name: '306979-mx'
},
{
name: '066195-o1',
_children: [],
},
];
$(function() {
let innerHtml = '<ul>';
data.forEach( item => {
innerHTML += '<li>' + '<div>' + item.name + '</div>';
if(item._children) {
// ***ISSUE*** this doesn't print all the children so i cannot recursively get all the children
console.log('children', item._children);
}
});
innerHtml += '</ul>';
});
Expected output
<ul>
<li> <div>Name1</div>
<ul>
<li><div>Name2</div>
.... continue the next unordered list until all children have been displayed ...
</ul>
</li>
</ul>
2
Answers
For your requirement, the recursive solution seems more intuitive to me. Let me share my insights for approaching this:
References:
?.
)As you seem to be using jQuery, here is a solution using jQuery style, producing the object structure, ready to inject in the HTML document:
An advantage of setting the text with
text()
, is that you’ll not have issues if the item’s name has character sequences that could be misinterpreted as HTML, such as<
or&
in combination with other characters.