Created
August 5, 2019 16:01
-
-
Save jeffscottward/d03093016355043ef5d083cf83118949 to your computer and use it in GitHub Desktop.
Recursive Depth Traversal of JSON to Build DOM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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