I am currently trying to turn a JSON object generated by a parser into nested checkboxes of the form:
<ul>
<li>
<label><input type="checkbox" data-id="netherlands" data-name="Netherlands"> Netherlands</label>
<ul>
<li>
<label><input type="checkbox" data-id="north-holland" data-name="North Holland"> North Holland</label>
<ul>
<li><label><input type="checkbox" data-id="amsterdam" data-name="Amsterdam"> Amsterdam</label></li>
<li><label><input type="checkbox" data-id="haarlem" data-name="Haarlem"> Haarlem</label></li>
<li><label><input type="checkbox" data-name="Alkmaar"> Alkmaar</label></li>
</ul>
</li>
<li>
<label><input type="checkbox" data-id="south-holland" data-name="South Holland"> South Holland</label>
<ul>
<li><label><input type="checkbox" data-id="the-hague" data-name="The Hague"> The Hague</label></li>
<li><label><input type="checkbox" data-id="rotterdam" data-name="Rotterdam"> Rotterdam</label></li>
<li><label><input type="checkbox" data-name="Gouda"> Gouda</label></li>
</ul>
</li>
</ul>
</li>
</ul>
The JSON I am working with looks like:
{
"category1": {
"subCategory1": {
"subCategory2": {
"subCategory3": {
"test1": {
"testCaseInfo": "some info"
}
}
}
}
},
"category2": {
"subCategory1": {
"test1": {
"testCaseInfo": "some info"
}
}
}
}
I need to take this JSON and turn it into checkboxes like the example above. The problem I am running to is that the "bottom level" of nesting are the tests, eg. test1, but those are also objects to it is difficult to dynamically know when to stop nesting and just make a list of the tests. I have a recursive function currently that almost works but not quite due to the problem I have just mentioned.
Current code:
function iterObj(obj) {
for (var key in obj) {
if (obj[key] !== null && typeof obj[key] === "object") {
html += "<ul>\n<li>\n<label><input class='form-check-input' type='checkbox' >"+key+"</label>\n";
iterObj(obj[key]);
html += "</ul></li>"
}
else if ($.isArray(obj[key])) {
html += "<ul>"
for (var i=0; i<obj[key].length; i++) {
html += "<li><label><input class='form-check-input' type='checkbox' >"+key[i]+"</label></li>\n"
}
html += "</ul>\n"
}
}
}
I don't hit the isArray case when I desire, because inside the array are objects of test names and info, so when I try to make a list of those I still end up hitting the object case and not getting what I want.
Aucun commentaire:
Enregistrer un commentaire