In this post we will show you how to build the sample JSON object and from that how to build the tree structure.

Creating Sample JSON

  1. var jsonData = [];
  2. var item0 = {};
  3. item0.ID = '100', item0.Title = 'Manager', item0.Department = 'IT', item0.Location = 'Hyderabad';
  4. var item1 = {};
  5. item1.ID = '101', item1.Title = 'Ramakrishna Basagalla', item1.Department = 'IT', item1.Location = 'Hyderabad', item1.Lead = '100';
  6. var item2 = {};
  7. item2.ID = '102', item2.Title = 'Praveenkumar Basagalla', item2.Department = 'BS', item2.Location = 'Bangalore', item2.Lead = '100';
  8. var item3 = {};
  9. item3.ID = '103', item3.Title = 'Indraneel', item3.Department = 'IT', item3.Location = 'Hyderabad', item3.Lead = '101';
  10. var item4 = {};
  11. item4.ID = '104', item4.Title = 'Neelohith', item4.Department = 'IT', item4.Location = 'Hyderabad', item4.Lead = '101';
  12. var item5 = {};
  13. item5.ID = '105', item5.Title = 'Pavan', item5.Department = 'BS', item5.Location = 'Bangalore', item5.Lead = '102';
  14. jsonData[0] = item0, jsonData[1] = item1, jsonData[2] = item2, jsonData[3] = item3, jsonData[4] = item4, jsonData[5] = item5;

Function to build Tree structure JSON

  1. var BuildTreeStructure = function () {
  2. var treeJson = [];
  3. var children = [];
  4. // build tree structure.
  5. for (i = 0; i < jsonData.length; i++) {
  6. var item = jsonData[i];
  7. var parentid = item.Lead;
  8. var id = item.ID;
  9. if (children[parentid]) {
  10. if (!children[parentid].children) {
  11. children[parentid].children = [];
  12. }
  13. children[parentid].children[children[parentid].children.length] = item;
  14. children[id] = item;
  15. }
  16. else {
  17. children[id] = item;
  18. treeJson[id] = children[id];
  19. }
  20. }
  21. return treeJson;
  22. }

Calling the BuildTreeStructure function on page load

  1. $(document).ready(function(){
  2. var finaJson = BuildTreeStructure();
  3. });

Output