I need to make two loops from one data point to create multiple divs.
Data Example:
let data = [
[
{
title: '1'
},
{
title: '2'
}
],
[
{
title: '3'
},
{
title: '4'
}
]
];
If I loop in here, I get 2 arrays with 2 sets of obj each.
I need to append a parent div for each array and inside the appended div, loop again to append the information from the obj.
To look something like this:
<div class="first-array"> //Class is just for reference
<span>
<p>title</p>
</span>
<span>
<p>title</p>
</span>
</div>
<div class="second-array"> //Class is just for reference
<span>
<p>title</p>
</span>
<span>
<p>title</p>
</span>
</div>
How can I be able to achieve this?
You can use Array.map to wrap each nested item's title property in the appropriate tags, then use Array.join to convert the array to a string:
let data=[[{title:"1"},{title:"2"}],[{title:"3"},{title:"4"}]];
const HTML = data.map(e => '<div>'+e.map(f => `<span><p>${f.title}</p></span>`).join('')+'</div>').join('')
console.log(HTML);
document.write(HTML);
jQuery's .append() can take an array of objects so you can map your original data to the structure you want
let data = [[{"title":"1"},{"title":"2"}],[{"title":"3"},{"title":"4"}]]
$(document.body).append(data.map(titles =>
$("<div>").append(titles.map(({ title: text }) =>
$("<span>").append($("<p>", { text }))))))
div, span, p {
display: block;
border: 1px solid;
padding: .5rem;
margin: .5rem;
position: relative;
}
div:after, span:after, p:after {
position: absolute;
font-size: 0.6em;
color: gray;
top: 0;
left: 0;
}
div:after { content: "div"; }
span:after { content: "span"; }
p:after { content: "p"; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>