我需要使用下面的 json 对象构建嵌套无序列表,每个 json 对象都有 id 和父 id,根或顶部元素父 id 为 0
JSON Object
{
"menu": [
{"id":1,"name":"Dashboard","parent":0},
{"id":2,"name":"Dashboard1","parent":0 },
{"id":3,"name":"Dashboard2","parent":0},
{"id":4,"name":"Dashboard3","parent":0},
{"id":5,"name":"Dashboard4","parent":1},
{"id":6,"name":"Dashboard5","parent":1},
{"id":7,"name":"Dashboard6","parent":1},
{"id":8,"name":"Dashboard7","parent":2},
{"id":9,"name":"Dashboard8","parent":5}
]
}
预期结果 :
<ul class="menu" >
<li >Dashboard</li>
<li >Dashboard1
<ul>
<li> Dashboard4</li>
<li> Dashboard5
<ul>
<li> Dashboard8</li>
</ul>
</li>
<li> Dashboard6</li>
</ul>
</li>
<li >Dashboard2
<ul>
<li> Dashboard7</li>
</ul>
</li>
<li >Dashboard3</li>
</ul>
我试过了
menuArr=[];
$.each(menu,function(i,val){
var parent=$(".menu");
if(val.parent!=0){
parent= menuArr[val.parent];
}
menuLi= $('<li>'+val.name+'</li>');
parent.append(menuli);
menuArr[val.id]=menuli;
});