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 do I save code using loops while accessing json data?

I recently started my first programming project. I started noticing that I use the same code over and over again, and would like to save that.

Here is an example:

   document.getElementById('Serie1').textContent = showtrend.tv_results[0].title ;
   document.getElementById('Serie1ID').textContent = "https://www.imdb.com/title/"+showtrend.tv_results[0].imdb_id ;
   document.getElementById('Serie1Year').textContent = showtrend.tv_results[0].year ;

   document.getElementById('Serie2').textContent = showtrend.tv_results[1].title ;
   document.getElementById('Serie2ID').textContent = "https://www.imdb.com/title/"+showtrend.tv_results[1].imdb_id ;
   document.getElementById('Serie2Year').textContent = showtrend.tv_results[1].year ;

I am basically adding the values I get in form of a json from my api to my site.

But how can I put all of this in a loop? It is like that for another 10 series, ant isn't very elegant

Would really appreciate the help

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

0

How I would do:

ECMAScript

const BASE_URL = "https://www.imdb.com/title/";

showtrend.tv_results.forEach(function (result, i) {
    let count = i + 1;
    document.getElementById(`Serie${count}`).textContent = result.title;
    document.getElementById(`Serie${count}ID`).textContent = BASE_URL + result.imdb_id;
    document.getElementById(`Serie${count}Year`).textContent = result.year;
});

Vanilla JS

const BASE_URL = "https://www.imdb.com/title/";

for(var i = 1; i <= showtrend.tv_results.length; i++) {
    document.getElementById('Serie' + i).textContent = result.title;
    document.getElementById('Serie' + i + 'ID').textContent = BASE_URL + result.imdb_id;
    document.getElementById('Serie' + i + 'Year').textContent = result.year;
});

In addition, maybe as your next challenge, try to get rid of these hard-coded elements in the list of "series" and make it dynamically created by pushing elements to an array in Javascript and populating a table or a list reading from this array. This will keep your code even more elegant.

Good luck with your studies!

about 4 years ago · Juan Pablo Isaza Relatório

0

I think this might help you.

for (let i = 1; i < showtrend.tv_results.length; i++) {
    var name = 'Serie'+ i;
    document.getElementById(name).textContent = showtrend.tv_results[i-1].title ;
    document.getElementById(name+'ID').textContent = "https://www.imdb.com/title/"+showtrend.tv_results[i-1].imdb_id ;
    document.getElementById(name+'Year').textContent = showtrend.tv_results[i-1].year ;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Instead of having predefined elements in your page that you have to fill, have one container element, and then iterate over the tv_results array and compile the information from each object into divs, or a table, and then insert that HTML as the innerHTML of the container.

This method will allow you to have as many movies in the data as you need.

const json = '{"showtrend": {"tv_results": [{ "title": "Batman", "imdb_id": 1 },{ "title": "Ratman", "imdb_id": 2 }]}}';

const data = JSON.parse(json);

// Pass in the parsed data
function getHTML(data) {

  // `map` over the tv_results array
  return data.showtrend.tv_results.map(obj => {
    
    // For each object in the iteration return a string of HTML.
    // This method uses a template literal, and adds
    // a data attribute to the outer div to identify the movie.
    return (
      `<div data-id="${obj.imdb_id}" class="movie">
         <div>${obj.title}</div>
         <div>${obj.imdb_id}</div>
       </div>`
    );

  // Finally join the array that `map` returns
  // and return that string
  }).join('');
}

// Cache the container element
const container = document.querySelector('#container');

// Call `getHTML` and add the returned HTML string
// to the `innerHTML` of the container
container.innerHTML = getHTML(data);
.movie { margin-bottom: 0.5em; background-color: #efefef; padding: 0.2em; }
<div id="container"></div>

Additional documentation

  • querySelector

  • Template/string literals

  • map

  • join

  • Data attributes

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