1 回答
TA贡献2080条经验 获得超4个赞
尝试这样做。
var array = [
{"id":"1", "idType": "1", "name": "FCB", "Members": [{"name": "Lionel"},{"name": "Pique"}], "idParent": ""},
{"id":"2", "idType": "2", "name": "Football", "Members": [{"name": "Pique"}], "idParent": "1"},
{"id":"3", "idType": "2", "name": "Basketball", "Members": [{"name": "Pique"}], "idParent": "1"},
{"id":"4", "idType": "3", "name": "UEFA 14", "Members": [{"name": "Test"}], "idParent": "2"},
{"id":"5", "idType": "3", "name": "UEFA 15", "Members": [{"name": "Carlos"}], "idParent": "2"},
{"id":"6", "idType": "3", "name": "NBA 15", "Members": [], "idParent": "3"},
{"id":"7", "idType": "4", "name": "Team 1", "Members": [{"name": "Lionel"},{"name": "Pique"}], "idParent": "4"},
{"id":"8", "idType": "4", "name": "Team 2", "Members": [{"name": "Lionel"}], "idParent": "4"},
]
function create_jstree(array){
var resultArray = [];
array.forEach((element) => {
let object1;
if(element.idParent!=""){
object1 = {
"text": element.name,
"id":element.id,
"children": createMembers(element)
}
let index=resultArray.findIndex( (resElement)=>resElement.id==element.idParent);
if( index == -1){
findParentAndPushChild(element,object1,resultArray)
}
else{
resultArray[index].children.push(object1);
}
}
else{
object1 = {
"text": element.name,
"id":element.id,
"children": createMembers(element)
}
resultArray.push(object1);
}
});
return resultArray;
}
function findParentAndPushChild(element,object,resArray){
resArray.forEach( (child)=> {
if(child.id == element.idParent){
child.children.push(object);
return;
}
else if(child.children.length!=0){
findParentAndPushChild(element,object,child.children);
}
});
}
function createMembers(element) {
let tempArr=[];
if (element.Members && element.Members.length!=0) {
tempArr.push({
"text": "Members",
"children": element.Members.map((member) => {
return {
"text": member.name,
"children": []
}
})
})
}
return tempArr;
}
$(function() {
$("#jstree_try").jstree({
'core' : {
'themes': {
'responsive': true
},
'data' : create_jstree(array)
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.9/themes/default/style.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.9/jstree.min.js"></script>
<div id="jstree_try"></div>
- 1 回答
- 0 关注
- 66 浏览
添加回答
举报