HTML Tree Diagram using JSON data
So I've got some JSON like this (keys/values changed for privacy reasons).
It's basically an Object with a "children" array of Objects, with each
element having its own "children" array of Objects, et cetera.
{
"name": "Main Area",
"children": [
{
"name": "Sub-section A",
"children": [
{
"name": "Procedure 1"
"children": [
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
}
]
},
{
"name": "Procedure 2"
"children": [
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
}
]
},
{
"name": "Procedure 3"
"children": [
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
},
{
"name": "Sub-procedure A",
"children": null
}
]
},
]
}
]
}
... and it's possible that that gets several times larger/deeper as I go
along. The goal here is to transform this data into a (collapsable) tree
diagram and then showing it on a HTML page using knockout.js (preferably).
All the logic has to be JavaScript code though (grab JSON with jQuery
AJAX, treat it in some way, show it).
Like this only then rotated 90 degrees so it goes down and not to the
side.
http://www.education.vic.gov.au/images/content/studentlearning/mathscontinuum/icecream.gif
Now I know that there are libraries like jsTree out there, but the point
is that I want this to be a learning experience as well so I want to
create my own code here. Also, jsTree prints its structures like a
directory tree. The thing I'm looking for is a more visual top-down tree
diagram that fills the whole width of the page.
Thing is, I'm stuck. I just can't wrap my head around all these nested
arrays/objects. I've probably spent about 3 hours trying things, creating
several different functions to iterate recursively through the entire
array but I can't get it to work right.
The latest idea that crossed my mind was to somehow go through the JSON
structure, starting from the deepest element, moving upwards, somehow
translating the steps into tree diagram levels, until I reach the top, at
which point it's finished.
So, willing to point me in the right direction? You don't have to write
dozens of lines of code for me, just give me an indication, some
pseudocode perhaps, of where I should take this.
Thanks in advance!
No comments:
Post a Comment