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

144
Visualizações
How to fix Javascript associative array error

I am trying to display a list of images with their titles stored in an associative array. But the code only displays the last image and title in the array, in the browser not all of them. However when I console log the values: value.title and value .image the full list is displayed in the console. I must be missing something simple any pointers would be welcome.

<center id="pics"></center>
    <script>
      const photos = [
        {
          title: "Landscape River",
          image: "landscape1.png",
        },
        {
          title: "Landscape Mountains",
          image: "landscape2.png",
        },
        {
          title: "Landscape Mountain Road",
          image: "landscape3.png",
        },
        {
          title: "Landscape Hills and Lake",
          image: "landscape4.png",
        },
      ];

      photos.forEach((value) => {
        console.log(value.title, value.image);
       
          document.getElementById("pics").innerHTML =
            `<img src="images/${value.image}" >` + "<br>" + value.title;
        
      });
    </script>
  </body>

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

0

You will want to do document.getElementById("pics").innerHTML += instead of just =. You want to append each title and image, and not reset the innerHTML every time with a new title/image if that makes sense. Happy coding!

about 4 years ago · Juan Pablo Isaza Relatório

0

While the accepted answer kind of works, it is a not a good solution, because it leads to totally unnecessary re-rendering of the DOM with every loop iteration. And that is just the performance side of the story; using innerHTML also is bad security-wise.

Instead, create those elements dynamically using document.createElement, append it to a documentFragment, and when the loop is done, append that fragment to the actual DOM.

That being said, this is what a proper solution could look like:

const picsContainer = document.getElementById("pics");
const fragment = new DocumentFragment();
photos.forEach(({image, title}) => {
  const img = document.createElement('img');
  img.src = `images/${image}`;
  const br = document.createElement('br');
  const text = document.createTextNode(title);
  fragment.append(img, br, text);        
});
picsContainer.append(fragment);
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