Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

364
Visualizações
In forEach loop, only last value is shown

I am using the MET API to show the information of each art piece in a specific department. To do this I am trying to loop through an array, first10, using forEach. When I look in the console.log, I can see each objs in first10, but once it gets to object.onload, I only get the "card" of the last objs in the array.

This is the HTML:

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">    
        </head>
    
        <body id="home">
            <main id="results-container"></main>
            <script src="js/script.js" type="text/javascript"></script>
        </body>
    </html>

This is the JavaScript:

let resultsBody = document.getElementById('results-container');

      objects.open('GET', `https://collectionapi.metmuseum.org/public/collection/v1/objects?departmentIds=6`, true);
      objects.onload = function() {
        let data2 = JSON.parse(this.response);
        if (objects.status >= 200 && objects.status < 400) {
          let first10 = data2.objectIDs.slice(0, 4);
          intr = 0;
          first10.forEach(objs => {
            object.open('GET', `https://collectionapi.metmuseum.org/public/collection/v1/objects/${objs}`, true);
            object.onload = function() {
              let data3 = JSON.parse(this.response);
              if (object.status >= 200 && object.status < 400) {
                  const card = document.createElement('div');
                  card.setAttribute('class', 'card');
                  const images = document.createElement('div');
                  images.innerHTML = `<img src="${data3['primaryImageSmall']}">`;

                  const h1 = document.createElement('h1');
                  h1.style.color = "black";
                  h1.textContent = data3['title'];

                  const p = document.createElement('p');
                  p.style.color = "black";
                  p.textContent = data3['artistDisplayName'];

                  resultsBody.appendChild(card);
                  card.appendChild(images);
                  card.appendChild(h1);
                  card.appendChild(p);
                // }
              }
            }
            object.send();
          });
        }
      }
      objects.send();

I have been trying to figure out how to make a "card" with the information of each objs. I have been looking at other questions that relate to mine, but I did not really understand how it applies to my problem since I am still starting in JavaScript.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think you should declare new XMLHttpRequest(); in each every forEach iteration:

first10.forEach(objs => {
 /*HERE*/ let object  = new XMLHttpRequest(); 
 object.open('GET', `https://collectionapi.metmuseum.org/public/collection/v1/objects/${objs}`, true);

otherwise you're re-assigning the new calls for the same object so you get the last one only.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda