console.table
does exactly what I need it to do. But I want that table to be outputted in the browser. How can I do this?
I've tried a few other solutions that didn't work because either:
My Object looks like this:
{
source0: {target0: 2, target1: 2, target2: 1},
source1: {target1: 3},
/*...*/
}
Here's a solution, with two iterations, the first one to find the columns and the second one to build the table :
var s = {
source0: {target0: 2, target1: 2, target2: 1},
source1: {target1: 3},
}
var cols = [];
for (var k in s) {
for (var c in s[k]) {
if (cols.indexOf(c)===-1) cols.push(c);
}
}
var html = '<table><tr>'+
cols.map(function(c){ return '<th>'+c+'</th>' }).join('')+
'</tr>';
for (var l in s) {
html += '<tr>'+
cols.map(function(c){ return '<td>'+(s[l][c]||'')+'</td>' }).join('')+
'</tr>';
}
html += '</table>';
demonstration
Of course you'd have to tailor it for your exact need. For example if you want to have the keys of the properties.
You should use a templating system for this.
Here is an example with Handlebars.js http://jsfiddle.net/x6r5fbw1/ (you can also run snippet below)
$(function(){
var data = {
source0: {target0: 2, target1: 2, target2: 1},
source1: {target1: 3},
},
table = [],
colsDict = {},
key = "",
innerKey = "",
tableData = [],
tmp = Handlebars.compile($("#template").text()),
html = "";
for (key in data) {
if (data.hasOwnProperty(key)) {
table.push({title:key});
for (innerKey in data[key]){
if (data[key].hasOwnProperty(innerKey)) {
table[table.length-1][innerKey] = data[key][innerKey];
colsDict[innerKey] = ""; } } } }
var cols = ["title"];
for (key in colsDict){
if (colsDict.hasOwnProperty(key)){
cols.push(key); } }
for (key in table){
var obj = {};
for (innerKey in cols){
if (table[key].hasOwnProperty(cols[innerKey])) {
obj[cols[innerKey]] = table[key][cols[innerKey]]; }
else{
obj[cols[innerKey]] = ""; } }
tableData.push(obj); }
html = tmp({cols: cols, rows:tableData});
$("#target").html(html);
});
<div id="target"></div>
<script language="text/template" id="template">
<table>
<tr>
{{#each cols}}
<th>{{this}}</th>
{{/each}}
</tr>
{{#each rows}}
<tr>
{{#each this}}
<td>{{this}}</td>
{{/each}}
</tr>
{{/each}}
</table>
</script>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With