Skip to content

Instantly share code, notes, and snippets.

@jeffscottward
Created August 5, 2019 16:01
Show Gist options
  • Save jeffscottward/d03093016355043ef5d083cf83118949 to your computer and use it in GitHub Desktop.
Save jeffscottward/d03093016355043ef5d083cf83118949 to your computer and use it in GitHub Desktop.
Recursive Depth Traversal of JSON to Build DOM
let data = [
{
title: "menu 1",
children :[
{ title: "menu 1.1"},
{
title: "menu 1.2",
children: [
{title: "menu 1.2.1"},
{title: "menu 1.2.2"},
]
},
]
},
{
title: "menu 2",
children :[
{ title: "menu 2.1"},
{ title: "menu 2.2"},
]
}
]
function buildTree(data, isChild = false) {
let html = '<ul>'
data.forEach(element => {
html += `<li>${d.title}</li>`
// If the current data element
// has children then call the
// buildTree again passing in
// the children and isChild = true
if(d.children) {
html += buildTree(d.children, true)
}
});
html += '</ul>'
return html
}
let uls = buildTree(data);
console.log(uls);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment