let a = {
name: "Alexander",
surname: "Pushkin",
fathername: "Sergeevich",
}
let b = {
name: "Taras",
surname: "Shevchenko",
sex: "male"
}
let c = {
name: "Nicolay",
surname: "Gogol",
age: 25,
}
let persons = [a, b, c]
let str2 = "<table border='1'>"
str2 += "<tr><th>Person</th><th>name</th><th>surname</th><th>age</th><th>fathername</th><th>sex</th></tr>"
for(let i = 0; i < persons.length; i++){
if(i % 2 == 1){
str2 += `<tr><td>${i}</td>
<td>${persons[i]["name"]}</td>
<td>${persons[i]["surname"]}</td>
<td>${persons[i]["age"]}</td>
<td>${persons[i]["fathername"]}</td>
<td>${persons[i]["sex"]}</td></tr>`
}
else{
str2 += `<tr style='background: cyan'><td>${i}</td>
<td>${persons[i]["name"]}</td>
<td>${persons[i]["surname"]}</td>
<td>${persons[i]["age"]}</td>
<td>${persons[i]["fathername"]}</td>
<td>${persons[i]["sex"]}</td></tr>`
}
}
str2
str2 += "</table>"
document.write(str2)
const columns = [ '#', ...new Set(persons.flatMap(Object.keys)) ];
// или
const columns = [ '#' ].concat(Object.keys(Object.assign({}, ...persons)));
document.body.insertAdjacentHTML('beforeend', `
<table>
<thead>
<tr>${columns.map(col => `
<th>${col}</th>`).join('')}
</tr>
</thead>
<tbody>${persons.map((person, i) => `
<tr>${columns.map((col, j) => `
<td>${j ? person[col] ?? '-' : i}</td>`).join('')}
</tr>`).join('')}
</tbody>
</table>
`);
const table = document.createElement('table');
table.createTHead().insertRow().append(...columns.reduce((acc, col) => (
(acc[acc.length] = document.createElement('th')).textContent = col,
acc
), []));
persons.forEach(function(person, i) {
columns.forEach(function(col, j) {
this.insertCell().textContent = j ? person[col] ?? '-' : i;
}, this.insertRow());
}, table.createTBody());
document.body.append(table);
let headers = persons.reduce((a,b)=>a.concat(Object.keys(b)),[]).filter((v, i, s)=>s.indexOf(v) === i);
str = `<table border='1'><tr>${headers.map(e=>`<th>${e}</th>`).join("\n")}</tr>` + persons.map(e=>`<tr>${headers.map(e1=>`<td>${e[e1]?e[e1]:"-"}</td>`).join("\n")}</tr>`).join("\n")+`</table>`;