Reputation: 76
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
Upvotes: 0
Views: 362
Reputation: 43
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;
});
Upvotes: 0
Reputation: 2008
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/
Upvotes: 1