Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I would like to generate an HTML tree (preferably UL-LI) from the JSON example below. Does anyone have a simple, recursive JS function (not a framework) that can handle this specific structure? Thanks for your help!

{ "folder" : [ {
    "title" : "1",
    "folder" : [ {
        "title" : "1.1",
        "folder" : [ {
            "title" : "1.1.1",
        } , {
            "title" : "1.1.2",
        } ]
    } ]
} , {
    "title" : "2",
} ] }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
150 views
Welcome To Ask or Share your Answers For Others

1 Answer

function to_ul (obj) {
  // --------v create an <ul> element
  var f, li, ul = document.createElement ("ul");
  // --v loop through its children
  for (f = 0; f < obj.folder.length; f++) {
    li = document.createElement ("li");
    li.appendChild (document.createTextNode (obj.folder[f].title));
    // if the child has a 'folder' prop on its own, call me again
    if (obj.folder[f].folder) {
      li.appendChild (to_ul (obj.folder[f].folder));
    }
    ul.appendChild (li);
  }
  return ul;
}

Caveat: No error checking! If a 'title' or 'folder' is missing, the whole thing could blow up.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...