console.table
完全符合我的要求。但我希望该表在浏览器中输出。我怎么能这样做?
我尝试过其他一些无效的解决方案,因为:
我的对象看起来像这样:
{
source0: {target0: 2, target1: 2, target2: 1},
source1: {target1: 3},
/*...*/
}
答案 0 :(得分:2)
这是一个解决方案,有两个迭代,第一个用于查找列,第二个用于构建表:
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>';
当然,您必须根据您的确切需要定制它。 For example if you want to have the keys of the properties
答案 1 :(得分:1)
你应该使用模板系统。
以下是Handlebars.js http://jsfiddle.net/x6r5fbw1/的示例(您也可以在下面运行代码段)
$(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>