JSFiddle - React, Tailwind, and code Playground
by ArktekniK
HTML
<div id="box"></div>
CSS
table > thead {
text-transform: capitalize;
}
JavaScript
function createTableFromObjectArray(dataSet) {
// List of unique keys in the data set
var dataKeys = dataSet.reduce(function(keys, element) {
for (key in element) {
keys.indexOf(key) === -1 ? keys.push(key) : '';
}
return keys;
}, []);
var html = "<table border='1|1'>";
// Create head of the table based on unique keys
html += "<thead><tr>";
for (var i = 0; i < dataKeys.length; i++) {
html += "<td>" + dataKeys[i] + "</td>";
}
html += "</tr></thead>";
// Create body of table
html += "<tbody>";
// Loop through dataset
for (var i = 0; i < data.length; i++) {
html += "<tr>";
// Loop through all the keys out objects *should* have
for (var j = 0; j < dataKeys.length; j++) {
var val = dataSet[i][dataKeys[j]];
// Create a row in the table, and insert the value of that key (or '-')
html += "<td>" + (val === undefined ? '-' : val) + "</td>";
}
html += "</tr>";
}
html += "</tbody></table>";
return html;
}
// Take some array of objects (with or without the same keys)
var data = /*[{
name: "John",
age: 20,
email: "[email protected]"
}, {
name: "Jack",
age: 50,
email: "[email protected]"
}, {
name: "Son",
age: 45,
email: "[email protected]",
comments: 'something!'
}];*/
[
{
"id": "SAMPLE_SESSION_ID_23",
"start": 1459501200000,
"end": 1459502522000,
"users": {
"male": 13,
"female": 33
},
"ages": [
30,
51,
38,
36,
24,
31,
42,
45,
42,
31,
44,
49,
33,
22,
51,
50,
52,
38,
44,
32,
43,
50,
27,
49,
61,
55,
46,
53,
27,
22,
41,
37,
42,
44,
33,
44,
33,
46,
47,
31,
38,
61,
44,
...