jQuery create nested list from JSON

I am trying to bend some existing code with my limited jQuery knowledge, be nice, im learning, I am trying to make a nested list with links, the end result would be the top level of the list being "category" then a nested UL with links using "url" and "text".

enter image description here

(I don’t care If the top level is linked, I can modify that part of the code)

Any help would be apprciated.

$(document).ready(function () {
    var $ul = $('<ul></ul>');
    var usefullinks = [
  {
    "category": "Category 2",
    "links": [
      {
        "url": "https://example.org",
        "text": "Some Link"
      }
    ]
  },
  {
    "category": "Test",
    "links": [
      {
        "url": "http://google.net",
        "text": "Link 1"
      },
      {
        "url": "https://example.com",
        "text": "Link 2"
      }
    ]
  }
];
    getList(usefullinks, $ul);
    $ul.appendTo(".main");
});

function getList(item, $list) {
    
    if($.isArray(item)){
        $.each(item, function (key, value) {
            getList(value, $list);
        });
        return;
    }
    
    if (item) {
        var $li = $('<li/>');
        if (item.category) {
            $li.append($('<a href="#">' + item.category + '</a>'));
        }
        if (item.links && item.links.length) {
            var $sublist = $('<ul/>');
            getList(item.links, $sublist);
            $li.append($sublist);
        }
        $list.append($li)
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">

</div>

>Solution :

Your recursive function is fine, you’ve just forgotten to do anything with url and text

if (item) {
    var $li = $('<li/>');
    if (item.category) {
        $li.append($('<a href="#">' + item.category + '</a>'));
    }

    // 👇
    if (item.text) {
        $li.append($(`<${item.url ? 'a' : 'span'}/>`, {
            href: item.url,
            text: item.text
        });
    }
    // 👆

    if (item.links && item.links.length) {
        var $sublist = $('<ul/>');
        getList(item.links, $sublist);
        $li.append($sublist);
    }
    $list.append($li)
}

Leave a Reply