premasagar/tim

Nested List

Closed this issue · 1 comments

I'm trying to render nested json to created nested list. is there a simple way to do this?

If you can share an example it will be helpful.

<ul>
  <li>
     <h2>One</h2>
     <ul>
        <li>One 1</li>
         <li>One 2</li>
     </ul>
  </li>
  <li>
     <h2>Two</h2>
     <ul>
        <li>Two 1</li>
         <li>Two2</li>
     </ul>
  </li>
</ul>
[
    {
        "name": "One",
        "items": [
            {
                "itemname": "One 1"
            },
            {
                "itemname": "One 2"
            }
        ]
    },
    {
        "name": "Two",
        "items": [
            {
                "itemname": "Two 1"
            },
            {
                "itemname": "Two 2"
            }
        ]
    }
]

I figured out a way as specified below

var listitems = [
    {
        "name": "One",
        "items": [
            {
                "itemname": "One 1"
            },
            {
                "itemname": "One 2"
            }
        ]
    },
    {
        "name": "Two",
        "items": [
            {
                "itemname": "Two 1"
            },
            {
                "itemname": "Two 2"
            }
        ]
    }
];
var myList = "";
var listitem = '<li><a href="#">{{itemname}}</a></li>';
var mainNav = '<li> <h2 >{{name}}</h2> <ul> {{listitem}} </ul> </li>';

for (i=0; i<(listitems.length); i++){
   var itemchilds = listitems[i].items;
   var myListItem = "";
   for (j=0;j<(itemchilds.length);j++){
        myListItem += tim(listitem, {itemname: itemchilds[j].itemname});
   }
   myList += tim(mainNav, {name: listitems[i].name,listitem : myListItem});
}