问题描述
我尝试了两个单独的ajax查询JSON对象列表并获取json列表,如下所示:
listperson = [
{
Id: 25,name: "person1"
},{
Id: 26,name: "person2"
}
];
listPersonDetails=
[
{
personId:25,lecture: "math",score:80
},{
personId:25,lecture: "chm",score:95
},{
personId:26,score:60
}
]
然后我尝试显示树视图;但我无法转换它。如何在jstree中合并并转换为这样的树视图:
----person1
-person1 info 1
-person1 info 2
----person2
-person2 info 1
-person2 info 2
解决方法
试试这个:
var listperson = [{
Id: 25,name: 'person1'
},{
Id: 26,name: 'person2'
}
];
var listPersonDetails = [{
personId: 25,lecture: 'math',score: 80
},{
personId: 25,lecture: 'chm',score: 95
},{
personId: 26,score: 60
}
]
var jstreedata = [];
//convert to the necessary JSON format
$.each(listperson,function(indexperson,person) {
jstreedata.push({
'text': person.name,'state': {
'opened': true,'selected': false
},'children': []
});
$.each(listPersonDetails,function(indexdetails,details) {
if (person.Id == details.personId) {
jstreedata[indexperson]['children'].push({
'text': details.lecture,'li_attr': {
'title': 'Score = ' + details.score
}
})
};
});
});
//create jsTree
$(function() {
$('#jstree_demo_div').jstree({
'core': {
'data': jstreedata
}
});
});
<link rel="stylesheet" href="dist/themes/default/style.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<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.2.1/jstree.min.js"></script>
<div id="jstree_demo_div"></div>
循环遍历两个数组并将合并的结果添加到 jsTree JSON format 中的新数组中。输出如下所示:
[
{
"text": "person1","state": {
"opened": true,"selected": false
},"children": [
{
"text": "math","li_attr": {
"title": "Score = 80"
}
},{
"text": "chm","li_attr": {
"title": "Score = 95"
}
}
]
},{
"text": "person2","li_attr": {
"title": "Score = 60"
}
}
]
}
]