I need to convert a JSON response to nested div elements and append them using jquery. For example, my JSON response is something like this.
[
{
name: "List one",
arr: [
{key: "A1"},
{key: "B1"},
{key: "C1"},
{key: "D1"}
]
},
{
name: "List two",
arr: [
{key: "A2"},
{key: "B2"},
{key: "C2"},
{key: "D2"}
]
},
{...},
{...}
]
and I need to build a div structure like this
<ul>
<li>List one</li>
<ul>
<li>A1</li>
<li>B1</li>
<li>C1</li>
<li>D1</li>
</ul>
<li>List two</li>
<ul>
<li>A2</li>
<li>B2</li>
<li>C2</li>
<li>D2</li>
</ul>
.......
</ul>
Currently this is how I tried,
jsonObject.forEach((item)=>{
var subCategories = item.arr.forEach((subCat)=>{
return `<li class="list-group-item">${subCat.key}</li>`
})
$('#nested').append(
`<li class="list-group-item">
${item.name}
<ul>
${subCategories}
</ul>
</li>`
);
});
This is somewhat similar to React method. But I am getting undefined for subCategories. How do I achieve something like this using jquery?
mapinstead ofeachandgetafter themap.mapand thenjointhe array. Thanks gurvinder