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

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

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 Denunciar

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 Denunciar

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 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