Peyo Peev
Peyo Peev

Reputation: 117

List JS object array

I have a an array in js it's something like this

menu = [
        {
            name: 'Item1',
            //submenuName: 'submenu-1',
        },
        {
            name: 'Item2',
            submenuName: 'submenu-2',
            sub: [
                {
                    name: 'Item2_1',
                    //submenuName: '',
                },
                {
                    name: 'Item2_2',
                    //submenuName: '',
                },
                {
                    name: 'Item2_3',
                    //submenuName: '',
                }
            ]
        },
        {
            name: 'Item3',
            //submenuName: 'submenu-3',
        }
    ]

And i need to list them in ul tag, but every level has to be closed before the other.

<ul data-menu="main">
  <li data-submenu>Item1</li>
  <li data-submenu='submenu-2'>Item2</li>
  <li data-submenu>Item3</li>
</ul>
<ul data-menu="submenu-2">
  <li data-submenu>Item2_1</li>
  <li data-submenu>Item2_2</li>
  <li data-submenu>Item2_3</li>
</ul>

and so on. I've mange to print them but only the first level. Cannot print the sub level.

Upvotes: 0

Views: 223

Answers (1)

Rafael
Rafael

Reputation: 18522

If the menus need to be listed one after another and not nested, then maintain an array of menus to print and fill that array with submenus while printing parent menus.

Since you mentioned, that you're using jQuery, here is an example using this library.

function generateMenu (menu, container) {
  var menus = [{name: 'main', entries: menu}];

  while (menus.length) {
    var current = menus.shift();

    var ul = $("<ul />").attr('data-menu', current.name);

    $.each(current.entries, function (index, menuItem) {
      var li = $('<li />')
                  .attr('data-submenu', menuItem.submenuName || '')
                  .text(menuItem.name);

      if ($.isArray(menuItem.sub)) {
        menus.push({name: menuItem.submenuName, entries: menuItem.sub});
      }

      li.appendTo(ul);
    });

    ul.appendTo(container);
  }
}

generateMenu(menu, $('body'));

JSFiddle example

Upvotes: 1

Related Questions