ak85
ak85

Reputation: 4264

creating list with sub items from json structure

I am creating a list with the below code which is contained in this fiddle.

<ul></ul>


var myList = [{
        "title": "Home",
            "sub": 0,
            "url": "/home",
            "show": 1
    }, {
        "title": "News",
            "sub": 0,
            "url": "/news",
            "show": 1
    }, {
        "title": "About",
            "sub": 1,
            "url": "/about",
            "show": 1,
        child: [{
            "title": "Contact",
                "sub": 0,
                "url": "/about/contact",
                "show": 1
        }]
    }, {
        "title": "Other",
            "sub": 0,
            "url": "/other",
            "show": 0
    }];

    $.each(myList, function (entryIndex, entry) {
        var title = this.title;
        var show = "";
        var sub = '';
        var url = this.url;
        if (!this.show) {
            show = "style=color:grey;";
        }
        if (this.sub) {
            sub = $("ul").append(this.child.text);
            console.log(sub);
        }
        $("ul").append("<li " + show + "> " + title + sub + "</li>");
    });

The output I am getting is, which is working as expected except for the children of about.

<ul>
    <li> Home</li>
    <li> News</li>
    <li> About[object Object]</li>
    <li style="color:grey;"> Other</li>
</ul>

How do I go about getting the children to appear so I get

<ul>
    <li> Home</li>
    <li> News</li>
    <li> About
        <ul>
           <li> Contact</li>
        </ul>
    </li>
    <li style="color:grey;"> Other</li>
</ul>

Upvotes: 0

Views: 847

Answers (1)

Dalorzo
Dalorzo

Reputation: 20014

Try something like this:

Online Demo

$(document).on('ready',function(){

var data =  [{/*... your data*/}] ;

var endMenu =getMenu(data);

    function getMenu(d ){
          return d.map(function(node){

              var subMenu = ( node.child && node.child.length > 0) ? '<ul>'+ getMenu(node.child) + '</ul>' : "";
               return '<li>'+node.title +  subMenu + '</li>' ;
           });
       }
      $('#menu').html('<ul>'+endMenu.join('')+ '</ul>');
});

All you have to do is to check is your object has child items and if does you execute the function again getMenu(node.child), like:

var subMenu = ( node.child && node.child.length > 0) ? '<ul>'+ getMenu(node.child) + '</ul>' : "";

Hopefully this will guide you to implement it in you version.

Upvotes: 2

Related Questions