I've written a function to create an HTML tree from JSON.
async function traverseTree (list, node) {
const li = document.createElement('li')
if (node.kids) {
const
ul = document.createElement('ul'),
span = document.createElement('span')
span.innerText = node.name
li.appendChild(span)
li.appendChild(ul)
list.appendChild(li)
for (const kid of node.kids) {
traverse(ul, kid)
}
return list
}
li.innerText = node.name
list.appendChild(li)
return list
}
;(async function(){
const
tree = await readJson('./tree.json'),
list = document.createElement('ul'),
output = await traverseTree(list, tree)
console.log(output)
})()
The issue is that I don't want to display the root node in the HTML tree since it is already displayed elsewhere, therefore I modified the code to exclude it.
async function traverseTree (list, node, isNotRoot) { // additional parameter
const li = document.createElement('li')
if (node.kids) {
let ul = list // now let
if (isNotRoot) { // additional conditional
const span = document.createElement('span')
ul = document.createElement('ul') // additional assignment of value
span.innerText = node.name
li.appendChild(span)
li.appendChild(ul)
list.appendChild(li)
}
for (const kid of node.kids) {
traverseTree(ul, kid, true) // additional argument
}
return list
}
li.innerText = node.name
list.appendChild(li)
return list
}
I'm wondering if there is a better, cleaner way to go about this?