I have an array of objects in which the fields may differ slightly.
when I build a table due to the fact that I do not have the same fields in objects, my table shrinks how can I make a table so that I have an empty line where there are no fields.
Dear colleagues, please tell me how to correctly complete this task.
you can use only pure javascript
const data = [
{
"#": 1,
"First Name": "Wilhelm Conrad",
"Last Name": "Röntgen",
"Born Location": "Lennep",
"Died Location": "Munich, Germany",
"Gender": "male",
"Prizes": "yes"
},
{
"#": 1,
"First Name": "Wilhelm Conrad",
"Last Name": "Röntgen",
"Born Location": "Lennep",
"Gender": "male",
"Prizes": "yes"
},
{
"#": 1,
"First Name": "Wilhelm Conrad",
"Last Name": "Röntgen",
"Born Location": "Lennep",
"Died Location": "Munich, Germany",
"Gender": "male",
"Prizes": "yes"
},
{
"#": 1,
"First Name": "Wilhelm Conrad",
"Last Name": "Röntgen",
"Born Location": "Lennep",
"Gender": "male",
"Prizes": "yes"
},
{
"#": 1,
"First Name": "Wilhelm Conrad",
"Last Name": "Röntgen",
"Born Location": "Lennep",
"Gender": "male",
"Prizes": "yes"
}
]
const keys = Object.keys(data[0])
let tab = document.createElement('table');
const buildTableHeader = () => {
let thead = document.createElement('thead');
let tr = document.createElement('tr');
for (const key of keys) {
const th = document.createElement("th");
th.appendChild(document.createTextNode(key));
tr.appendChild(th);
}
thead.appendChild(tr)
tab.appendChild(thead);
document.body.appendChild(tab)
}
let tb = document.createElement('tbody');
const buildTableBody = () => {
for (let a of data) {
let tr = document.createElement('tr');
for (let key in a) {
let td = document.createElement('td');
let tn = document.createTextNode(a[key]);
td.appendChild(tn);
tr.appendChild(td);
}
tb.appendChild(tr);
}
tab.appendChild(tb);
document.body.appendChild(tab);
}
buildTableHeader()
buildTableBody()
