JSFiddle - React, Tailwind, and code Playground
by Christopher Collins
CSS
.card-header {
color: #3BB273;
background-color: #fff;
}
.row {
background: #f8f9fa;
margin-top: 20px;
}
.col {
border: solid 1px #6c757d;
padding: 10px;
}
.table-striped thead tr {
color: #fff;
background-color: #2C83CF;
}
.table-striped tbody tr:nth-of-type(odd) {
background-color: rgba(44, 131, 207, 0.3);
}
JavaScript
var rows = [{
name: "John",
age: 20,
email: "xx@hotmail.com"
}, {
name: "Jack",
age: 50,
email: "xxx@hotmail.com"
}, {
name: "Son",
age: 45,
email: "xxxx@hotmail.com"
}];
const Array2Table = (arr) => {
let Table = [];
let top_row = [];
let rows = [];
for (let i = 0; i < arr.length; i++) {
let cells = [];
for (let property in arr[i]) {
if (top_row.length < Object.keys(arr[i]).length) {
top_row.push(`<th scope="col">${property}</th>`);
}
if (arr[i][property] === null) {
cells.push(`<td>${null}</td>`);
} else {
cells.push(`<td>${arr[i][property]}</td>`);
}
}
rows.push(`<tr>${cells.join("")}</tr>`);
}
Table.push(`<table class="table card-table table-striped">`);
Table.push(`<thead>${top_row.join("")}</thead>`);
Table.push(`<tbody>${rows.join("")}<tbody>`);
Table.push("</table>");
return Table.join("");
}
$(function() {
let html = Array2Table(rows);
$("div").html(html);
});