I need help showing all the items in an array with Javascript

Asked

Viewed 464 times

2

I am using AXIOS to access the API and can return only the first result.

I copied only one part of the code below, but everything works perfectly when I enter the index [0].

document.getElementById('results').innerHTML = `
                    <p><b>Nome: </b> ${item.products[0].name} </p>  
                    <p><b>Preço: </b> R$ ${item.products[0].priceMin} </p>`

I’ve tried countless ways to use a for loop to show the 12 items, but there’s no way to make it work.

I believe the requisition is correct, because when I execute a console.log(item.products);I can see the 12 results.

How can I make all the results appear within HTML?

Code that is not working:

function showResults (item) {                   
            var tamanho = item.products.length;
            for (i = 0; i < tamanho; i++) {                     
            document.getElementById('results').style.display = 'block'
                document.getElementById('results').innerHTML = `
                <p><b>Nome: </b> ${item.products[i].name} </p>  
                <p><b>Preço: </b> R$ ${item.products[i].priceMin} </p> `
                console.log(item.products);
            }

I am learning, so I joined what I learned with the tutorials. I don’t know if there is any nonsense.

  • 1

    You can provide an example of the returned JSON?

  • 1

    How’s the noose you’re wearing?

  • present us your tie for, maybe in it the problem

  • I just finished editing with my bow.

1 answer

3


The problem is that every time you see that it iterates you’re rewriting the previous content and rewriting...

Instead of using document.getElementById('results').innerHTML = you must use += to add, not replace.

That said, I suggest you use the .map or the .reduce that in my opinion are more practical for this type of tasks:

function showResults(item) {
  const html = item.products.reduce((html, product) => {
    return html + `
       <p><b>Nome: </b> ${product.name} </p>  
       <p><b>Preço: </b> R$ ${product.priceMin} </p>
    `;
  }, '');
  document.getElementById('results').style.display = 'block'
  document.getElementById('results').innerHTML = html;
}
  • Yesterday I forgot to mention this case: <p><b>Image: </b> <img src="${item.products[i].thumbnail.otherFormats[i]. url}" /></p> How do I access the values inside otherFormats? I’m getting Undefined.

  • @Joãofernandozanato in this case you must have another .map or for within what I have shown and use the same logic. In this case the array to iterate is product.thumbnail.otherFormats

Browser other questions tagged

You are not signed in. Login or sign up in order to post.