user499909
user499909

Reputation: 21

how to create dynamic tree structure with list of string paths using javascript

I have a list of strings with are paths to some file with "/" separator that are available to my jsp/html page . i.e.

d1/d2/d3/file1.c
d1/d2/d3/file2.java
d1/d2/file3.jsp
d1/d2/file4.asp
d1/d2/d3/d4/file4.asp
d11/d22/d33/file5.txt

The above list of string paths are available to my page. I need to make a dynamic tree structre with above data in below tree structure using javascript.

+d1/d2/
 file3.jsp
 file4.asp

+d1/d2/d3/
 file1.c
 file2.java

+d1/d2/d3/d4/
 file4.asp

+d11/d22/d33/
 file5.txt

When I click on the common path like +di/d2 it should expand to show all the files under that directory , and when again click on it should hide the child files. Simmilarly for all other nodes.

Upvotes: 2

Views: 4390

Answers (1)

LostInTheCode
LostInTheCode

Reputation: 1744

Since you have no code to show us, I'm not going to write it all for you. Just an overview, to tell you the method, you'll have to write your own code:

  1. Store the paths as strings in javascript
  2. Call string.split("/") on each of them and store results in arrays
  3. Create object that will hold the tree
  4. Match all top leveled arrays that are similar, and then append all of the unique top level directories as children to the object created in step 3.
  5. Continue process using a trickle-down method, adding children to the children of the top level directories.
  6. Render the results probably as a list, by appending the children to the list objects that you create, using the trickle down method again.

For reference: Javascript building tree hierarchy

Upvotes: 4

Related Questions