Two relational Json array merge and convert to treeview JStree

Viewed 58

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
1 Answers

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>

Loop through both arrays and add the combined result to a new array in the jsTree JSON format. The output looks like this:

[
  {
    "text": "person1",
    "state": {
      "opened": true,
      "selected": false
    },
    "children": [
      {
        "text": "math",
        "li_attr": {
          "title": "Score = 80"
        }
      },
      {
        "text": "chm",
        "li_attr": {
          "title": "Score = 95"
        }
      }
    ]
  },
  {
    "text": "person2",
    "state": {
      "opened": true,
      "selected": false
    },
    "children": [
      {
        "text": "math",
        "li_attr": {
          "title": "Score = 60"
        }
      }
    ]
  }
]
Related