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

146
Visualizações
¿Cómo guardo código usando bucles mientras accedo a datos json?

Recientemente comencé mi primer proyecto de programación. Empecé a notar que uso el mismo código una y otra vez y me gustaría guardarlo.

Aquí hay un ejemplo:

 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 ;

Básicamente, estoy agregando los valores que obtengo en forma de json desde mi API a mi sitio.

Pero, ¿cómo puedo poner todo esto en un bucle? Es así para otra serie 10, la hormiga no es muy elegante.

Realmente agradecería la ayuda

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

0

Como lo haría:

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; });

Vainilla 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; });

Además, tal vez como su próximo desafío, intente deshacerse de estos elementos codificados de forma rígida en la lista de "series" y cree dinámicamente empujando elementos a una matriz en Javascript y llenando una tabla o una lista leyendo de esta matriz . Esto mantendrá su código aún más elegante.

¡Buena suerte con sus estudios!

about 4 years ago · Juan Pablo Isaza Relatório

0

Creo que esto podría ayudarte.

 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

En lugar de tener elementos predefinidos en su página que debe completar, tenga un elemento contenedor y luego itere sobre la matriz tv_results y compile la información de cada objeto en divs, o una tabla, y luego inserte ese HTML como el HTML innerHTML del envase.

Este método le permitirá tener tantas películas en los datos como necesite.

 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>

Documentación adicional

  • querySelector

  • Plantilla/literales de cadena

  • map

  • join

  • Atributos de datos

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