Reputation: 91
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>
Upvotes: 1
Views: 783
Reputation: 28404
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)
Upvotes: 2
Reputation: 3856
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;
}
Upvotes: 1