Tech
Forums
Jobs
Books
Events
Interviews
Live
More
Learn
Training
Career
Members
Videos
News
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Building JSON Tree Structure in jQuery
WhatsApp
Ramakrishna Basagalla
10y
22.2
k
0
0
25
Blog
Building JSON Tree Structure in jQuery
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
var jsonData = [];
var item0 = {};
item0.ID =
'100'
, item0.Title =
'Manager'
, item0.Department =
'IT'
, item0.Location =
'Hyderabad'
;
var item1 = {};
item1.ID =
'101'
, item1.Title =
'Ramakrishna Basagalla'
, item1.Department =
'IT'
, item1.Location =
'Hyderabad'
, item1.Lead =
'100'
;
var item2 = {};
item2.ID =
'102'
, item2.Title =
'Praveenkumar Basagalla'
, item2.Department =
'BS'
, item2.Location =
'Bangalore'
, item2.Lead =
'100'
;
var item3 = {};
item3.ID =
'103'
, item3.Title =
'Indraneel'
, item3.Department =
'IT'
, item3.Location =
'Hyderabad'
, item3.Lead =
'101'
;
var item4 = {};
item4.ID =
'104'
, item4.Title =
'Neelohith'
, item4.Department =
'IT'
, item4.Location =
'Hyderabad'
, item4.Lead =
'101'
;
var item5 = {};
item5.ID =
'105'
, item5.Title =
'Pavan'
, item5.Department =
'BS'
, item5.Location =
'Bangalore'
, item5.Lead =
'102'
;
jsonData[0] = item0, jsonData[1] = item1, jsonData[2] = item2, jsonData[3] = item3, jsonData[4] = item4, jsonData[5] = item5;
Function to build Tree structure JSON
var BuildTreeStructure = function () {
var treeJson = [];
var children = [];
// build tree structure.
for
(i = 0; i < jsonData.length; i++) {
var item = jsonData[i];
var parentid = item.Lead;
var id = item.ID;
if
(children[parentid]) {
if
(!children[parentid].children) {
children[parentid].children = [];
}
children[parentid].children[children[parentid].children.length] = item;
children[id] = item;
}
else
{
children[id] = item;
treeJson[id] = children[id];
}
}
return
treeJson;
}
Calling the BuildTreeStructure function on page load
$(document).ready(function(){
var finaJson = BuildTreeStructure();
});
Output
Building JSON Tree Structure in jQuery
Up Next
Dynamic HTML Table or Grid from JSON using JQuery in SharePoint
Ebook Download
View all
Frontend Developer Interview Questions and Answers
Read by 940 people
Download Now!
Learn
View all
Membership not found