I am having trouble figuring out how to set the break condition for this recursive function. Currently, the function is causing the browser to freeze (seems to be stuck in an endless loop).
My goal is to create a series of nested unordered lists based on the data provided in the list object.
You can view the fiddle here: https://jsfiddle.net/mzckoc7s/
var list = {
"primary": [{
"item": "item 1"
}, {
"item": "item 2",
"secondary": [{
"item": "item secondary 1"
}, {
"item": "item secondary 2"
}, {
"item": "item secondary 3",
"secondary": [{
"item": "item inner secondary 1"
}]
}]
}, {
"item": "item 3"
}]
}
function items( obj ) {
var output = '<ul>';
for ( i = 0; i < obj.length; i++ ) {
output += '<li>' + obj[i].item + '</li>';
if (typeof obj[i].secondary != 'undefined') {
items( obj[i].secondary );
break;
}
}
output += '</ul>';
return output;
}
The expected result should look like this:
<ul>
<li>item 1</li>
<li>item 2
<ul>
<li>item secondary 1</li>
<li>item secondary 2</li>
<li>item secondary 3
<ul>
<li>item inner secondary 1</li>
</ul>
</li>
</ul>
</li>
<li>item 3</li>
</ul>