Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

362
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda