Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

javascript - Two relational Json array merge and convert to treeview JStree

I tried to two seperate ajax query JSON object list and get json list, like this:

listperson = [ 
{ 
  Id: 25,
  name: "person1"
 },
{
  Id: 26,
  name: "person2"
}
];

listPersonDetails= 
[
 { 
  personId:25,
  lecture: "math",
  score:80
 },
{ 
  personId:25,
  lecture: "chm",
  score:95
 },
{ 
  personId:26,
  lecture: "math",
  score:60
 }
]

And then I tried to display treeview; but I couldnt convert it . How can I merge and convert to treeview like this in jstree:

----person1
    -person1 info 1
    -person1 info 2
----person2
    -person2 info 1
    -person2 info 2
question from:https://stackoverflow.com/questions/65880725/two-relational-json-array-merge-and-convert-to-treeview-jstree

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try like this:

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,
    lecture: 'math',
    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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...