Home > Software design >  javascript loop create a row every 4 elements
javascript loop create a row every 4 elements

Time:08-12

I can't do my function, could someone help me, thank you. I have a json file with a lot of entries, I create html in js. I would like to create a row every 4 elements. I'm really sorry I can't format my code well

function createUserList(usersList) {

  usersList.forEach(user => {

    const listItem = document.createElement("div");
    listItem.setAttribute("class", "row");
    listItem.innerHTML = `
        <div >
            <a  href="single-portfolio.html">
                          <div >
                              <span >
                                <span >${user.type}</span><span style="color: #92C13B;">${user.nom}</span>
                              </span>
                            <figure >
                              <img src="images/${user.image}" alt="" width="418" height="315"/>
                            </figure>
                          </div>
                          <div >
                            <p >Compétences scientifiques,intérêt pour les technologies de laboratoire.</p>
                            <div ></div>
                            <p >Le BTS ABM est proposé à Toulouse, Montpellier et Lille.!</p>
                            <span ></span>
                          </div>
                        </a>
                      </div>`

    searchResult.appendChild(listItem);

  })
}


{

  "results": [{
      "nom": "Analyse Biologie Médical",
      "image": "MBS-phot-2.jpg",
      "type": "BTS"
    },
    {

      "nom": "Diététique",
      "image": "diet.webp",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "m2ns.jpg",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "dieteticien.jpg",
      "type": "BACHELOR"
    },
    {
      "nom": "Analyse Biologie Médical",
      "image": "MBS-phot-2.jpg",
      "type": "BTS"
    },
    {

      "nom": "Diététique",
      "image": "diet.webp",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "m2ns.jpg",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "dieteticien.jpg",
      "type": "BACHELOR"
    }
  ]
}

CodePudding user response:

Instead of creating a new element on each iteration use map to create a template string for each object, and then join that array of strings (map returns a new array) into one HTML string. Then assign that HTML to a containing element.

(Sidenote: if your data is tabular you should probably use a table.)

Here's a pared back example to show you how map/join work together.

const arr = [
  { name: 'Rita', nom: 18, img: 'img1' },
  { name: 'Sue', nom: 19, img: 'img2' },
  { name: 'Bob', nom: 40, img: 'img3' }
];

// Accepts the array of objects
function createHTML(arr) {

  // `map` returns a new array of HTML strings which
  // is `joined` up before that final string is returned
  // from the function
  return arr.map(obj => {
    const { name, nom, img } = obj;
    return `<div>${name} - ${nom} - ${img}</div>`;
  }).join('');
}

// Get the container and assign the result of calling the
// function with the array of objects
const container = document.querySelector('.container');
container.innerHTML = createHTML(arr);
<div ></div>

Additional documentation

CodePudding user response:

The following is an attempt on joining 4 divs into each row an the separating it with an <hr> from the next row:

function createUserList(usersList) {

  document.getElementById("searchresult").innerHTML=usersList.map((user,i) =>`${i&&!(i%4)?"<hr>":""}
<div >
 <a  href="single-portfolio.html">
  <div >
   <span >
    <span >${user.type}</span>
    <span style="color: #92C13B;">${user.nom}</span>
   </span>
   <figure >
    <img src="images/${user.image}" alt="" width="41.8" height="31.5"/>
   </figure>
  </div>
  <div >
   <p >Compétences scientifiques,intérêt pour les technologies de laboratoire.</p>
   <div ></div>
   <p >Le BTS ABM est proposé à Toulouse, Montpellier et Lille.!</p>
   <span ></span>
  </div>
 </a>
</div>`).join("")
}


const usrs= {

  "results": [{
      "nom": "Analyse Biologie Médical",
      "image": "MBS-phot-2.jpg",
      "type": "BTS"
    },
    {

      "nom": "Diététique",
      "image": "diet.webp",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "m2ns.jpg",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "dieteticien.jpg",
      "type": "BACHELOR"
    },
    {
      "nom": "Analyse Biologie Médical",
      "image": "MBS-phot-2.jpg",
      "type": "BTS"
    },
    {

      "nom": "Diététique",
      "image": "diet.webp",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "m2ns.jpg",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "dieteticien.jpg",
      "type": "BACHELOR"
    }
  ]
}
createUserList(usrs.results)
.isotope-item {display:inline-block}
<h2>Results</h2>
<div id="searchresult"></div>

  • Related