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

164
Visualizações
How can i add row to html table from a list of objects

The object created every time the submit button is clicked , and it pushed to the book_list array but i get messy when i loop in the list to create a row , how can i solve this ? here is the link : https://jsfiddle.net/s7jmkeqL/

let book = new Book(title.value, authName.value, email.value, price.value, date.value, lang.value, radio.value);
book_list.push(book);

// create new rows
function createTd(content) {
  let td = document.createElement('td');
  td.appendChild(document.createTextNode(content));
  tr.appendChild(td);
  table.appendChild(tr);
}

book_list.sort((a, b) => (a.date > b.date) ? 1 : -1); // sort the list by date

for (let i = 0; i < book_list.length; i++) {
  createTd(book_list[i].date);
  createTd(book_list[i].authName);
  createTd(book_list[i].email);
  createTd(book_list[i].title);
  createTd(book_list[i].type);
  createTd(book_list[i].price);
  createTd(book_list[i].lang);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I believe the problem is, as soon as you create a <td>, you add it to a <tr> but you also immediately append this <tr> to your table. As a result, your table gets filled with <tr> containing only one <td>.

Also I rewrote your for loop so as to avoid repeating yourself, and also make the book keys dynamic, in case you want to add more later (rating, recap, etc. for instance)

let tr;

function createTd(content) {
  let td = document.createElement('td');
  td.appendChild(document.createTextNode(content));
  tr.appendChild(td);
}

const keys = Object.keys(book_list[0]); // ["date","authName",...]

for (let book of books) {
  tr = document.createElement('tr'); // Create a new row for each book

  for(let key of keys) {
    createTd(book[key]); // Append all the cells in the same row
  }

  table.appendChild(tr); // Add the row to the table
}
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