flyingL123
flyingL123

Reputation: 8076

Javascript create hierarchical list of variable depth

I have a list of categories, each of which has an array of children categories, which themselves can contain children. I'm trying to create a list of the categories, with each category also containing a sublist of it's children.

My HTML is simply the container for the top-level list:

<ul id="categories"></ul>

Then I have the following Javascript:

function addCategories($list, cats) {
        $.each(cats, function(i, cat) {
                $item = $('<li><a href="#">' + cat.name + '</a></li>');

                if(cat.children.length) {
                        $subList = $('<ul></ul>');
                        $item.append($subList);
                        addCategories($subList, cat.children);
                }

                $list.append($item);
        });
}

var categories = [
    {
        "name": "Category 1",
        "children": []
    },
    {
        "name": "Category 2",
        "children": [
            {
                "name": "Subcategory 2",
                "children": [
                    {
                        "name": "Subsubcategory 2",
                        "children": []
                    }
                 ]
            }
         ]
    },
    {
        "name": "Category 3",
        "children":[]
    }
];

$(function() {
   addCategories($('#categories'), categories); 
});

What I would like to see is:

<ul id="categories">
    <li>
        <a href="#">Category 1</a>
    </li>
    <li>
        <a href="#">Category 2</a>
        <ul>
            <li>
                <a href="#">Subcategory 2</a>
                <ul>
                    <li>
                        <a href="#">Subsubcategory 2</a>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
    <li>
        <a href="#">Category 3</a>
    </li>
</ul>

However, instead I see:

<ul id="categories">
    <li>
        <a href="#">Category 1</a>
    </li>
    <li>
        <a href="#">Subsubcategory 2</a>
    </li>
    <li>
        <a href="#">Category 3</a>
    </li>
</ul>

Here's a fiddle: http://jsfiddle.net/qacf2mn6/

What am I doing wrong?

Upvotes: 0

Views: 887

Answers (1)

flyingL123
flyingL123

Reputation: 8076

Figured it out. I was missing var declarations, so it wasn't resetting the variables.

Here's the correct js code:

function addCategories($list, cats) {
        _.each(cats, function(cat) {
                var $item = $('<li><a href="#">' + cat.name + '</a></li>');

                if(cat.children.length) {
                        var $subList = $('<ul></ul>');
                        $item.append($subList);
                        addCategories($subList, cat.children);
                }

                $list.append($item);
        });
}

Upvotes: 2

Related Questions