How can I build a nested UL structure from an object of paths using JavaScript?
For example given the following array of paths:
var paths = [
"d1/d2/d3/file1.txt",
"d1/d2/d3/file2.txt",
];
I would like to build the following UL
<ul class="base-UL">
<li class="folder">d1
<ul>
<li class="folder">d2
<ul>
<li class="folder">d3
<ul>
<li class="file" data-url="d1/d2/d3/file1.text">file1.text</li>
<li class="file" data-url="d1/d2/d3/file2.text">file2.text</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
How should I build a recursive function that does this?
Edit I was able to succefully write a function which does this however, I can't figure out how to get the full path as the data attribute in the file elements: See below:
function buildFromPathList(paths) {
for (var i = 0, path; path = paths[i]; ++i) {
var pathParts = path.split("/");
var subObj = tree_;
for (var j = 0, folderName; folderName = pathParts[j]; ++j) {
if (!subObj[folderName]) {
subObj[folderName] = j < pathParts.length - 1 ? {} : null;
}
subObj = subObj[folderName];
}
}
return tree_;
}
function render(object) {
for (var folder in object) {
if (!object[folder]) {
var name = folder.trim();
html_ += '<li class="file>' + folder + '</li>';
} else {
html_ += '<li class="folder">' + folder + '<ul>';
render(object[folder]);
html_ += "</ul>";
}
}
}
var html_ = [];
render(buildFromPathList(paths));