I'm trying to build a HTML list using a recursive loop from an object structured like this – there are an infinite number of levels of possible depth:
object = {
"directories":{
"vegetables":{
"info":{
"name":"Vegetables"
},
"files":{
},
"directories":{
"green vegetables":{
"info":{
"name":"Green Vegetables"
},
"files":{
},
"directories":{
"lettuce":{
"info":{
"name":"Lettuce"
},
"files":{
}
},
"cucumber":{
"info":{
"name":"Cucumber"
},
"files":{
}
}
}
},
"orange vegetables":{
"info":{
"name":"Orange Vegetables"
},
"files":{
},
"directories":{
"3 deep":{
"info":{
"name":"Carrot"
},
"files":{
}
}
}
}
}
},
"fruit":{
"info":{
"name":"Fruit"
},
"files":{
},
"directories":{
"apple":{
"info":{
"name":"Apple"
},
"files":{
}
}
}
}
}
}
The loop should create a nested html list as follows:
<ul>
<li>Vegetables
<ul>
<li>Green Vegetables
<ul>
<li>Lettuce</li>
<li>Cucumber</li>
</ul>
</li>
<li>Orange Vegetables
<ul>
<li>Carrot</li>
</ul>
</li>
</ul>
</li>
<li>Fruit
<ul>
<li>Apple</li>
</ul>
</li>
</ul>
Currently my function looks like this, but currently it gets stuck after the first list item and I'm struggling to get my head around how to call itself correctly recursively:
function loopFilters(val){
app.navList.push('<ul>');
$.each(val.directories, function(i, val) {
app.navList.push('<li>' + directory);
if(val){
// console.log('yes', val.directories);
app.core.addFiltersToPage(val.directories)
}
app.navList.push('</li>');
});
app.navList.push('</ul>');
}
How can I rewrite my function to work with my Javascript object?
directoryin line 4 toval.info.name? Also, change condition toif (val.directories)and inside the if callloopFilters(val). Should work then