0

This is my menu layout in html

<ul>
   <li>Item A
       <ul>
           <li>Item A1</li>
           <li>Item A2</li>
       </ul>
   </li>
   <li>Item B
       <ul>
           <li>Item B1</li>
           <li>Item B2</li>
           <li>Item B3</li>
       </ul>
   </li>
</ul>

How to convert this layout to below Multi-dimensional associative JS array ?

var nav = [
    { "title" : "Item A",
      "submenu" : [ "Item A1", "Item A2" ] },
    { "title" : "Item B",
      "submenu" : [ "Item B1", "Item B2", "Item B3"] }
];

Please someone tell me how to do this

2
  • Iterate the elements and build the array, did you give it a try? A loop for outer elements (Item A, Item B) and a nested loop for inner elements (Item A1..). Commented Aug 28, 2015 at 17:10
  • Please write it's code Commented Aug 28, 2015 at 17:20

2 Answers 2

1

You need to each li and after each children of li for extract the submenu

var finalObj=new Array();
$("ul li:not(ul li ul li)").each(function(){

    var objtime=new Object();


    objtime.title=$(this).clone()   
    .children() 
    .remove() 
    .end() 
    .text().trim();


    var tempArray=new Array();
    $(this).children("ul").children("li").each(function(){
        tempArray.push($(this).text());
    });
    objtime.subtitle=tempArray;
    finalObj.push(objtime);
});

http://jsfiddle.net/e6vq1m4m/2/

Sign up to request clarification or add additional context in comments.

Comments

0

If i understood correctly, you may want to do something like this.

var menuArray = [],
      subArray;
  $('ul.first > li').each(function(i){
    var firstMenu = $.trim( $(this).find("a:first").text() );
    subArray = [];
    $(this).find('ul > li a').each(function(i){
      var secondMenu = $.trim( $(this).filter("a").text() );
      subArray.push(secondMenu);
    });
    menuArray[firstMenu] = subArray;
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.