How can you get a multiple output in json in just one loop?

Viewed 101

I did fetch from the URL and I got the data from forEach my problem is there is 2 div inside innerHTML with col-6 so it will be 2 column in 1 row so it will look like this -> sample image but i wanted to get the next line of the array on the second div is that possible so it will have 2 different data

 fetch(URL)
.then(data=>data.json())
.then(data=>{
 data.forEach(datas => {
document.querySelector('.more-from').innerHTML += `
<div class="row related">

 <div class="col-md-6 col-lg-6">
  <a href="${datas.post_name}"><div class="post position-relative mb-4" style="background-image:url('${datas.image}'); height:175px;">
  </div></a>
  <a href="${datas.post_name}" rel="bookmark" title="Permanent Link to ${datas.post_title}" class="post-title"><span style="font-weight:bold; font-family:oswald, 
  sans-serif !important;font-size: 17px; line-height: 22px; color: #333;">${datas.post_title} 
  </span></a>
 </div>

  <div class="col-md-6 col-lg-6">
  <a href="${datas.post_name}"><div class="post position-relative mb-4" style="background-image:url('${datas.image}'); height:175px;">
  </div></a>
  <a href="${datas.post_name}" rel="bookmark" title="Permanent Link to ${datas.post_title}" class="post-title"><span style="font-weight:bold; font-family:oswald, 
  sans-serif !important;font-size: 17px; line-height: 22px; color: #333;">${datas.post_title} 
  </span></a>
 </div>

</div>`;

ITS ONLY GETTING THE FIRST ID WHICH IS 10893 FOR BOTH DIV. Console log of data

2 Answers

Just use a regular for with index:

for(let i = 0; i < data.length - 1; i = i + 2) {
    const div1Data = data[i];
    const div2Data = data[i+1]
    document.querySelector('.more-from').innerHTML += `...`
}

I would use a normal for loop as @Onheiron suggests, only I would use a modulo check to get less repetitive code.

e.g.

for(let i = 0; i < data.length - 1; i = i++) {

    if(i % 2 === 0)
        document.querySelector('.more-from').innerHTML += `<row>`;
   
    document.querySelector('.more-from').innerHTML += `<your element only once>`

    if(i % 2 === 0)
        document.querySelector('.more-from').innerHTML += `</row>`;
}

if you'd set the value to check the modulo against to a variable you could also easily change it to get 3 columns.

Related