I am trying to covert a JSON file to HTML using vanilla JavaScript. The way I approached it appears to be working but the code is not ideal.
What I am doing is checking to see if the value of the key is an object. If so, this is a new HTML tag. If not then this is a attribute for the tag.
The problem that I am having is that I don't know how to properly loop through an object and test these conditions without duplicating my code.
Can someone help me identify how I can better write this?
function createComponent(component, defaults, map) {
Object.keys(defaults).forEach(function (level1) {
if (typeof defaults[level1] === "object") {
var tag = document.createElement(level1);
Object.keys(defaults[level1]).forEach(function (level2) {
if (typeof defaults[level1][level2] === "object") {
tag.appendChild(document.createElement(level2));
Object.keys(defaults[level1][level2]).forEach(function (level3) {
if (typeof defaults[level1][level2][level3] === "object") {
console.log(defaults[level1][level2][level3]);
tag.appendChild(document.createElement(level3));
}
});
}
});
}
});
}
createComponent("textBox", textBoxDefaults, map);
Pseudo code:
Check defaults object, is there an object at this level? If so, create an HTML tag with the same Key name. Is there values that are not objects? If so, add attributes to the created tag using the key value pair. Stop diving deeper into the JSON when you don't find anymore objects.
Sample JSON
textbox: {
id: 1,
name: "Text Box",
tmprops: {
cur: 0,
min: 5000,
visible: true,
},
tmctxlst: {
version: "2",
txttmctx: {
alwysshw: false,
name: "default"
}
},
Desired Output
<textbox id="1" name="text box">
<tmprops cur="0" min="5000" visible="true" />
<tmctxlst version="2">
<txttmctx alwysshow="false" name="default">
</tmctxlst>
</textbox>