Reputation: 16157
I am trying to create an html list with a recursive function in javascript, but I really don't understand why the actual result doesn't match my expect result.
Json
{
"sections": {
"1": {
"name": "Section 1",
"sections": {
"3": {
"name": "Section 1.1",
"sections": {
"4": {
"name": "Section 1.1.1",
"sections": {}
}
}
}
}
},
"2": {
"name": "Section 2",
"sections": {}
}
}
}
Javascript
$(document).ready(function() {
generateHtml(myLoadedJson);
});
function generateHtml(pData) {
var self = this;
var html = '';
if("sections" in pData) {
html+= '<ul>';
var objList = Object.keys(pData.sections);
var nbr = objList.length;
for(i=0; i<nbr; i++) {
var key = objList[i];
var obj = pData.sections[key];
html+= '<li><div>' + obj.name + '</div>'
html+= generateHtml(pData.sections[key]);
html+= '</li>';
}
html+= '</ul>';
}
return html;
};
Expected result
<ul>
<li>
<div>Section 1</div>
<ul>
<li>
<div>Section 1.1<div>
<ul>
<li>
<div>Section 1.1.1<div>
</li>
</ul>
</li>
</ul>
</li>
<li>
<div>Section 2</div>
</li>
</ul>
Actual result
<ul>
<li>
<div>Section 1</div>
<ul>
<li>
<div>Section 1.1</div>
<ul>
<li>
<div>section 1.1.1</div>
<ul></ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
Anyone have an idea?
Upvotes: 0
Views: 6677
Reputation: 188
The only mistake you have done is to use a global variable "i" in your loop.
for(i = 0; i < nbr; i++)
Instead, you should have written the statement as:
for(var i = 0; i < nbr; i++)
ensuring that you use a local variable for your loop.
You can see the working example using the following link
Upvotes: 0
Reputation: 47068
I think the problem is just in your for loop:
for(i = 0; i < nbr; i++)
should be:
for(var i=0; i<nbr; i++)
Essentially, all calls of the generateHtml(...)
function are sharing the same loop variable (i
). Therefore, when a sub-call increments i
the calling loops i
also increments. By adding var
you ensure that each call has it's own local variable.
Upvotes: 4