我想显示“翻转”(转置)数据表。例如。给出一些数据:
[{col1: "abc", col2: 123}, {col1: "xxx", col2: 321}]
显示为
+------+-----+-----+
| col1 | abc | xxx |
+------+-----+-----+
| col2 | 123 | 321 |
+------+-----+-----+
行应与标准表中的列相同。
是否有一些JS Ajax组件(如YUI DataTable或类似组件)可以执行此操作?
答案 0 :(得分:2)
好运动。我想这就是你想要的:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Transposed table</title>
</head>
<body>
<div id="wrapper"></div>
<script>
var tableData = [{col1: "abc", col2: 123},
{col1: "xxx", col2: 321}];
function rotateData(theTable) {
var result = [], i, j, key, keyFound;
for (i = 0; i < theTable.length; ++i) {
for (key in theTable[i]) {
/* now loop through result[] to see if key already exists */
keyFound = false;
for (j = 0; j < result.length; ++j) {
if (result[j][0] == key) {
keyFound = true;
break;
}
}
if (!keyFound) {
result.push([]); // add new empty array
result[j].push(key); // add first item (key)
}
result[j].push(theTable[i][key]);
}
}
return result;
}
function buildTable(theArray) {
var html = [], n = 0, i, j;
html[n++] = '<table>';
for (i = 0; i < theArray.length; ++i) {
html[n++] = '<tr>';
for (j = 0; j < theArray[i].length; ++j) {
html[n++] = '<td>';
html[n++] = theArray[i][j];
html[n++] = '</td>';
}
html[n++] = '</tr>';
}
html[n++] = '</table>';
return html.join('');
}
var rotated = rotateData(tableData);
var tableHtml = buildTable(rotated);
document.getElementById('wrapper').innerHTML = tableHtml;
</script>
</body>
</html>
函数rotateData
将对象的元素旋转到数组中,以便获得类似
[["col1", "abc", "xxx"], ["col2", 123, 321]]
为此,函数测试是否已经存在包含键的数组元素(在外部数组中),因此它可以将值添加到其“行”,或者它首先在外部数组中创建一个新元素,键入其第一个“列”,其值在第二个列中。
然后buildTable
创建必要的HTML,可以插入到可以包含表的每个元素。顺便说一句,该函数使用数组html
临时存储输出,最后连接其所有元素以返回字符串。这通常比(几乎)无休止地连接字符串更快。