-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddTable.js
111 lines (90 loc) · 3.05 KB
/
addTable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// thanks to https://jsfiddle.net/7og5348w/3/
function addTable(list, appendObj, depth) {
depth = depth || 0;
var columns = addAllColumnHeaders(list, appendObj);
for (var i = 0; i < list.length; i++) {
var row$ = $('<tr/>');
row$.addClass('depth-'+depth);
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = list[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
if (cellValue.constructor === Array)
{
$a = $('<td/>');
row$.append($a);
addTable(cellValue, $a, depth+1);
$a.addClass('col-'+columns[colIndex]);
} else if (cellValue.constructor === Object)
{
var array = $.map(cellValue, function (value, index) {
return [value];
});
$a = $('<td/>');
row$.append($a);
addObject(array, $a, depth+1);
$a.addClass('col-'+columns[colIndex]);
} else {
if (colIndex <= 1 ) {row$.addClass('row-'+cellValue);}
var $newTD = $('<td/>').html(cellValue);
row$.append($newTD);
$newTD.addClass('col-'+columns[colIndex]);
}
}
appendObj.append(row$);
}
}
function addObject(list, appendObj, depth) {
depth = depth || 0;
for (var i = 0; i < list.length; i++) {
var row$ = $('<tr/>');
row$.addClass('depth-'+depth);
var cellValue = list[i];
if (cellValue == null) {
cellValue = "";
}
if (cellValue.constructor === Array)
{
$a = $('<td/>');
row$.append($a);
addTable(cellValue, $a, depth+1);
$a.addClass('col-'+columns[colIndex]);
} else if (cellValue.constructor === Object)
{
var array = $.map(cellValue, function (value, index) {
return [value];
});
$a = $('<td/>');
row$.append($a);
addObject(array, $a, depth+1);
$a.addClass('col-'+columns[colIndex]);
} else {
var $newTD = $('<td/>').html(cellValue);
row$.append($newTD);
$newTD.addClass('col-');
}
appendObj.append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(list, appendObj)
{
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < list.length; i++) {
var rowHash = list[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
var $newTR = $('<th/>').html(key)
headerTr$.append($newTR);
$newTR.addClass('col-'+key);
}
}
}
appendObj.append(headerTr$);
return columnSet;
}