Imagine a JSON object of the following structure:
{
"dimension-1": {
"value1": "",
"value2": "",
"value3": "",
"value4": ""
},
"dimension-2": {
"value1": "",
"value2": "",
"value3": "",
"value4": "",
"dimension-2.1": {
"value1": "",
"dimension-2.2": {
"value1": ""
}
}
}
}
The object can have an unlimited number of nestings and the number is unknown.
What I want to create is a list that represents the JSON object by using the Vue List Rendering feature or something similar (if possible). At the end I would receive something like this:
<ul>
<li>
dimension-1
<ul>
<li>value-1</li>
<li>value-2</li>
<li>value-3</li>
<li>value-4</li>
</ul>
</li>
<li>
dimension-2
<ul>
<li>value-1</li>
<li>value-2</li>
<li>value-3</li>
<li>value-4</li>
<li>
dimension-2.1
<ul>
<li>value-1</li>
<li>
dimension-2.2
<ul>
<li>value1</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
With normal JS this is quite easy to do:
const object = {
"dimension-1": {
"value1": "",
"value2": "",
"value3": "",
"value4": ""
},
"dimension-2": {
"value1": "",
"value2": "",
"value3": "",
"value4": "",
"dimension-2.1": {
"value1": "",
"dimension-2.2": {
"value1": ""
}
}
}
}
function createHTML(json, isArray) {
var html = '<ul>';
for (var key in json) {
if (typeof json[key] == 'object') {
html += '<li>' + (!isArray ? '<strong>' + key + '</strong>' : '') + '</li>' + createHTML(json[key], (json[key] instanceof Array ? 1 : 0));
} else {
html += '<li>' + key + '</li>';
}
}
return html + '</ul>';
}
document.getElementById('output').innerHTML = createHTML(object, false);
<div id="output"></div>
However, this will obviously not work because of this part html += '<li>' + (!isArray ? '<strong>' + key + '</strong>' : '') + '</li>' + -->createHTML(json[key], (json[key] instanceof Array ? 1 : 0))<--;
.
So what is the solution to my problem or an alternative?