I have attempted various solutions for creating nested ul/li elements without success. I am a beginner in JavaScript and struggling with this task.
The data is retrieved after the page has loaded, and it looks like this:
data = {
"key1": ["value1", value2", "value3"],
"key2": ["value4", "value5", "value6"],
"key2": ["value7"]
}
Additionally, I would like to implement a feature where clicking on a key will expand to display its corresponding values. However, I have been unable to structure the data as shown below. The number of keys and their values can vary greatly, so flexibility is important.
<ul>
<li>
key1
<ul>
<li>value1</li>
<li>value2</li>
<li>value3</li>
</ul>
</li>
<li>
key2
<ul>
<li>value4</li>
<li>value5</li>
<li>value6</li>
</ul>
</li>
<li>
key3
<ul>
<li>value7</li>
</ul>
</li>
</ul>
Below is the jQuery code snippet that I have tried implementing. I have omitted it here as my attempts to achieve the desired nested structure have been unsuccessful.
jQuery(document).ready(function($) {
$.get('url', function(data){
var $ul = $('<ul></ul>');
function getList(item, $list) {
$.each(item, function (key, value) {
var $li = $('<li />');
$li.append($('<a href="#">' + key + '</a>'));
var $subul = $("<ul/>");
$.each(value, function(i) {
var subli = $('<li/>')
.text(value[i])
.appendTo(subli);
});
$subul.append(subli);
$li.append($subul)
});
}
getList(data, $ul);
$ul.appendTo("div_containing_ul");
});});