Last active
January 19, 2020 03:03
-
-
Save ekowcharles/e0a0cd53acb9b745b115c54893ce8b0a to your computer and use it in GitHub Desktop.
Convert JSON object to HTML list structure
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
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 + ': ' + 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