Skip to content

Instantly share code, notes, and snippets.

@ekowcharles
Last active January 19, 2020 03:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekowcharles/e0a0cd53acb9b745b115c54893ce8b0a to your computer and use it in GitHub Desktop.
Save ekowcharles/e0a0cd53acb9b745b115c54893ce8b0a to your computer and use it in GitHub Desktop.
Convert JSON object to HTML list structure
function isObject(obj) {
var type = typeof obj;
return (type === 'function' || type === 'object') && !!obj;
}
function isArray(obj) {
return obj instanceof Array
}
function build(obj) {
let list = [];
Object.keys(obj).forEach((key, _) => {
var v = obj[key];
list.push('<ul>')
if (isArray(v)) {
list.push('<li>' + key + '</li>')
v.forEach((k, _) => {
list.push('<ul>')
list.push(build(k))
list.push('</ul>')
})
} else if (isObject(v)) {
list.push('<li>' + key + '</li>')
list.push('<ul>')
list.push(build(v))
list.push('</ul>')
} else {
list.push('<li>' + key + ':&nbsp;&nbsp;' + v + '</li>')
}
list.push('</ul>')
})
return list;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment