Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading