微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

两个关系Json数组合并并转换为treeview JStree

如何解决两个关系Json数组合并并转换为treeview JStree

我尝试了两个单独的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"
        }
      }
    ]
  }
]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。