Is there a browser equivalent to `console.table`?
console.table
does exactly what I need it to do. But I want this table to be displayed in the browser. How can i do this?
I've tried several other solutions that didn't work because either:
- They expect an array of objects.
- Columns are not dynamically defined (i.e. my objects have no props).
My object looks like this:
{
source0: {target0: 2, target1: 2, target2: 1},
source1: {target1: 3},
/*...*/
}
+3
source to share
2 answers
Here's a solution with two iterations, the first to find the columns and the second 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>';
Of course, you will have to tailor it to your specific need. For example, if you want to have property keys .
+2
source to share
For this you have to use the template system.
Here is an example from Handlebars.js http://jsfiddle.net/x6r5fbw1/ (you can also run the 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>
+1
source to share