Dave Schuette Dave Schuette - 1 month ago 10
HTML Question

Converting nested lists to arrays

I have a nested unordered list on my page that looks something like this:

<ul id="myList">
<li><a href="link">Item 1</a></li>
<li><a href="link">Item 2</a>
<ul>
<li><a href="link">Sub Item 1</a></li>
<li><a href="link">Sub Item 2</a>
<ul>
<li><a href="link">Sub Sub Item 1</a></li>
<li><a href="link">Sub Sub Item 2</a></li>
</ul></li>
<li><a href="link">Sub Item 3</a></li>
</ul>
<li><a href="link">Item 3</a></li>
</ul>


I need to import it into javascript arrays that look like this:

var topLevel = ["Item 1", "Item 2", "Item 3"]
var subLevel = [
[],
["Sub Item 1", "Sub Item 2", "Sub Item 3"],
[],
]
var subSubLevel = [
[],
[
[],
["Sub Sub Item 1", "Sub Sub Item 2"],
[]
],
[]
]


I started with this, but it doesn't give me the nested arrays I need.

var topLevelList = $("#myList > li > a").map(function() { return $(this).text(); }).get();
var subLevelList = $("#myList > li > ul > li > a").map(function() { return $(this).text(); }).get();
var subSubLevelList = $("#myList > li > ul > li > ul > li > a").map(function() { return $(this).text(); }).get();

Answer

Here's what I ended up doing, for anyone in the future who searches for something similar...

_build = function(t){
    return {
        'name':$(t).find('> a').html(),
        'url':$(t).find('> a').prop('href'),
        'target':$(t).find('> a').prop('target'),
        'sub-items':[]
    };
}

var theStuff = [];
$('#interactiveList').find('> li').each(function(){
    var li_a = _build($(this));
    var b = $(this).children().find('> li');
    if (b) {
        b.each(function(){
            var li_b = _build($(this));
            var c = $(this).find('> ul li');
            if (c) {
                c.each(function(){
                    var li_c = _build($(this));
                    li_b['sub-items'].push(li_c);
                });
            }
            li_a['sub-items'].push(li_b);
        });
    }
    theStuff.push(li_a);
});