Skip to content

Instantly share code, notes, and snippets.

@tsmx
Created September 23, 2020 11:02
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 tsmx/63baac40b78689a738e1aad899931cd7 to your computer and use it in GitHub Desktop.
Save tsmx/63baac40b78689a738e1aad899931cd7 to your computer and use it in GitHub Desktop.
Create a HTML list from a JSON object. Supports simple nested objects and flat arrays.
function jsonToHtmlList(obj, level = 0) {
if (level == 0) {
console.log('<ul>');
}
else {
console.log((' ').repeat(level) + '<ul class=\"nested\">');
}
Object.entries(obj).forEach(([key, val]) => {
if (val !== null && typeof val == 'object' && !Array.isArray(val)) {
console.log((' ').repeat(level) + ' <li class=\"caret\">Key: ' + key + '</li>')
jsonToHtmlList(val, level + 1);
}
else {
console.log((' ').repeat(level) + ' <li>Key: ' + key + ', Value: ' + val + '</li>')
}
});
console.log((' ').repeat(level) + '</ul>');
}
const htmlTestobj = {
'arr': [0, 0],
'arr-in-arr': [0, 1, ['two', 'three', [4, 5, 6]]],
'number': 123,
'string': 'test',
'parent': {
'test': 1,
'child': {
'childval': 777
},
'array': [1, 2, 66, 9, 900]
},
'trail': 'testtesttest'
}
jsonToHtmlList(htmlTestobj);
// output:
//
// <ul>
// <li>Key: arr, Value: 0,0</li>
// <li>Key: arr-in-arr, Value: 0,1,two,three,4,5,6</li>
// <li>Key: number, Value: 123</li>
// <li>Key: string, Value: test</li>
// <li class="caret">Key: parent</li>
// <ul class="nested">
// <li>Key: test, Value: 1</li>
// <li class="caret">Key: child</li>
// <ul class="nested">
// <li>Key: childval, Value: 777</li>
// </ul>
// <li>Key: array, Value: 1,2,66,9,900</li>
// </ul>
// <li>Key: trail, Value: testtesttest</li>
// </ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment