0

I have a bit of code that loops through nested array (it can be unlimited in depth) and I am trying to generate a treelike structure from it.. of basically nested unordered lists..

Here is my fiddle http://jsfiddle.net/aj9TC/6/

I collect items names in a function like this:

function get_list( a ) {
    for (var i = 0; i < a.length; i++) {
         console.log( i + "---" + a[i].name );

         $(".mod-list ul").append('<li>' + a[i].name + '</li>');

         get_list( a[i].group );
     }
}

get_list( mods.group );

My sample html is simple

<h4>Nested List</h4>
<div class="mod-list">

    <ul class="list">

    </ul>

</div>

I currently append all items as li in a single unordered list,, but I need to create nested unordered lists that reflect the array nesting accurately.

Can someone help me out with this please.

Thanks!

3 Answers 3

3

What about this:

function get_list( a, $parent ) {
    var newUl = $("<ul></ul>");
    for (var i = 0; i < a.length; i++) {
        if (a[i]) {
            newUl.append('<li>' + a[i].name + '</li>');
            if (a[i].group)
                get_list( a[i].group, newUl );
        }

    }
    $parent.append(newUl);
}

get_list( mods.group, $(".mod-list"));

Here's a working fiddle: http://jsfiddle.net/aj9TC/7/

Sign up to request clarification or add additional context in comments.

Comments

1

Another solution that doesn't leave empty <ul>'s I also like to build up all my html and add it to the DOM once, instead of adding lots of little snippets.

function get_list( a, str ) {
    str += '<ul>';
    for (var i = 0; i < a.length; i++) {
        str += '<li>' + a[i].name;
        if (a[i].group && a[i].group.length) str += get_list( a[i].group, '' );
        str += '</li>';
    }
    str += '</ul>';
    return str;
}

$(".mod-list").append(get_list( mods.group, ''));

http://jsfiddle.net/aj9TC/8/

1 Comment

Thank you so very much. I find all three posted solutions useful but this one is the most practical for my actual use case. I appreciate the help.
1

Here's an approach that also builds all the html in array of strings and only does one append when done. Join array when ready to insert.

$(function(){
    var $list=$(get_list(mods.group,[]).join('')).addClass('list')
     $('.mod-list').append($list) 
});

function get_list(data, strArray) {
    strArray.push('<ul>');
    $.each(data, function(i, val) {
        strArray.push('<li>' + val.name);
        if (val.group) {
            get_list(val.group,strArray);
        }
        strArray.push('</li>');
    });
    strArray.push('</ul>');
    return strArray;
}

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.