gpt4 book ai didi

javascript - 有没有javascript数据表格组件把列显示为行?

转载 作者:行者123 更新时间:2023-11-29 15:05:32 24 4
gpt4 key购买 nike

我想显示一个“翻转”(转置)的数据表。例如。给定一些数据:

[{col1: "abc", col2: 123}, {col1: "xxx", col2: 321}]

显示为

+------+-----+-----+
| col1 |美国广播公司 | xxx |
+-----+-----+-----+
| col2 | 123 | 321 |
+-----+-----+-----+

行的行为应与标准表格中的列相同。

是否有一些 JS Ajax 组件(如 YUI DataTable 或类似组件)可以执行此操作?

最佳答案

不错的练习。我认为这就是您想要的:

<!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 来临时存储输出,最后连接它的所有元素以返回一个字符串。这通常比(几乎)无休止地连接一个字符串要快。

关于javascript - 有没有javascript数据表格组件把列显示为行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3475356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com