JSFiddle - React, Tailwind, and code Playground
by Steven Senkus
HTML
<ul id="output">
</ul>
JavaScript
const obj = {
"B": {},
"C": {
"F": {}
},
"D": {
"G": {},
"H": {
"I": {}
}
},
"E": {}
};
function getChildren(level) {
return Object.keys(level);
}
function hasChildren(obj) {
return Object.keys(obj).length > 0;
}
function ul(childLis) {
return `
<ul>
${childLis}
</ul>`;
}
function li(text, children) {
if (children) return `\n\t<li>${text}\n\t\t${children}</li>`;
return `\n\t<li>${text}</li>`;
}
let out = Object.keys(obj).reduce((accum, key) => {
function getHtml(item) {
if (hasChildren(item)) {
return getChildren(item);
} else {
return li(key);
}
}
let output = '';
const parent = obj[key];
console.log('key, val', key, obj[key], Object.keys(obj[key]).length);
if (hasChildren(parent)) {
let children = getChildren(parent);
output = li(key, ul(children.map(li).join('\n')));
} else {
output = li(key);
}
return accum + output;
}, '');
console.log('@@@', out);
document.getElementById('output').innerHTML = out;