'How to append properly when creating dynamic table or something else?
const users = [
{ id: 1, fName: "Ivan", lName: "Petrov", age: "30" },
{ id: 2, fName: "Petkan", lName: "Yordanov", age: "35" },
{ id: 3, fName: "Mincho", lName: "Praznikov", age: "20" },
{ id: 4, fName: "Sali", lName: "Mehmet", age: "40" },
{ id: 5, fName: "Hasan", lName: "Ivanov", age: "51" },
];
Creating a table in the HTML document
let table = document.createElement("table");
let tBody = document.createElement("tbody");
let tHead = document.createElement("thead");
Creating the header of the table with the keys from the array
Object.keys(users[0]).forEach((element) => {
let tHeader = document.createElement("th");
tHeader.innerText = element;
console.log(element);
tHead.append(tHeader);
});
table.append(tHead);
`Creating the rows `
users.forEach((user) => {
let tRow = document.createElement("tr");
Creating the data taken from the objects in the array
Object.keys(user).forEach((key) => {
let tData = document.createElement("td");
console.log(key);
tData.innerText = user[key];
tRow.append(tData);
});
tBody.append(tRow);
});
console.log(Object.keys(users[0]));
table.append(tBody);
document.body.append(table);
I am wondering if this is the best way do do this task and also if the way of appending the elements is correct ? I hope this time I write my question correctly. Thanks in Advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
