1

Why does this loop not produce a table with 7 rows? I have tried with a regular for loop, while, forEach. I'm missing something.

  const MOUNTAINS = [
    {name: "Kilimanjaro", height: 5895, place: "Tanzania"},
    {name: "Everest", height: 8848, place: "Nepal"},
    {name: "Mount Fuji", height: 3776, place: "Japan"},
    {name: "Vaalserberg", height: 323, place: "Netherlands"},
    {name: "Denali", height: 6168, place: "United States"},
    {name: "Popocatepetl", height: 5465, place: "Mexico"},
    {name: "Mont Blanc", height: 4808, place: "Italy/France"}
  ];


let makeTable = (arr) => {
  let table = document.createElement('table');
  let row = document.createElement('tr');
  let data = document.createElement('td');
  for (let entry of arr) {
    table.appendChild(row).appendChild(data);
  }
  return table;
}

makeTable(MOUNTAINS)

//<table>
//  <tr>
//    <td></td>
//  </tr>
//</table>


1
  • You might need to do something like document.body.appendChild(table) before the rest of the code. Commented Mar 4, 2021 at 19:33

2 Answers 2

2

You need to append it to the body at the end. Also, you're not filling out the data to the columns, what you can do is iterate over the entries, create a column data for each attribute and append it to the row which will be added to the table each time:

 const MOUNTAINS = [
    {name: "Kilimanjaro", height: 5895, place: "Tanzania"},
    {name: "Everest", height: 8848, place: "Nepal"},
    {name: "Mount Fuji", height: 3776, place: "Japan"},
    {name: "Vaalserberg", height: 323, place: "Netherlands"},
    {name: "Denali", height: 6168, place: "United States"},
    {name: "Popocatepetl", height: 5465, place: "Mexico"},
    {name: "Mont Blanc", height: 4808, place: "Italy/France"}
];


let makeTable = (arr) => {
  let table = document.createElement('table');
  for (let entry of arr) {
    let row = document.createElement('tr');
    Object.values(entry).forEach(value => {
      let data = document.createElement('td');
      data.appendChild(document.createTextNode(value));
      row.appendChild(data);
    });
    table.appendChild(row);
  }
  document.body.appendChild(table);
  return table;
}

makeTable(MOUNTAINS)

Sign up to request clarification or add additional context in comments.

Comments

0

because the elements must be unique, try this:

let makeTable = (arr) => {
  let table = document.createElement('table');
  for (let entry of arr) {
    let row = document.createElement('tr');
    let data = document.createElement('td');
    table.appendChild(row).appendChild(data);
  }
  return table;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.