我正在尝试使用 API 填充我的表格 HTML,但是,我想将给定的 HTML 表格填充到一列而不是一行中,以看起来像以下图像布局,但是,我被填充为行你可以在我的第二张图片中看到。有没有办法将其转换为基于列的填充?
行填充
const arr = [
{
"demo": [
{
"_id": "T0810",
"title": "Historian",
"tags": [
"demo"
],
"queries": [],
},
{
"_id": "T0817",
"title": "book",
"tags": [
"demo"
],
"queries": [],
},
],
"demo_2": [
{
"_id": "T0875",
"title": "Program",
"tags": [
"demo_2",
"Control"
],
"queries": [],
},
{
"_id": "T0807",
"title": "Interface",
"tags": [
"demo_2"
],
"queries": [],
}
]
}
]
const keys = Object.keys(arr[0]);
export default function Demo() {
return (
<div className="wrapper">
<table className="table">
<thead>
<tr>
{keys.map((i) => (
<th key={i}>
<div className="column">
<div className="header">{i}</div>
</div>
</th>
))}
</tr>
</thead>
<tbody>
{keys.map((key) => (
<tr key={key}>
{arr[0][key].map((item) => (
<td key={item._id}>
<div className="column">
<div className="option">{item._id}</div>
</div>
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
}
答案 0 :(得分:0)
这只是比你加在一起的稍微多一点。您必须考虑的第一件事是您的表格将有与最长键一样多的行,因此如果 demo
数组有 2 个元素而 demo_2
有 6 个元素,则表格将有 6 行,即使对于 demo
,其中 3 行不会显示任何内容。
因此,如果有意义的话,您的顶级循环将不得不循环而不是通过 keys
而是通过代表最长密钥长度的数字。因此,除了获取密钥之外,您还需要这样的东西:
const max_rows = keys.reduce((acc, cur) => {
if (arr[0][cur].length > acc) return arr[0][cur].length;
else return acc;
}, 0);
然后您的嵌套循环将如下所示:
<table className="table">
<thead>
<tr>
{keys.map((i) => (
<th key={i}>
<div className="column">
<div className="header">{i}</div>
</div>
</th>
))}
</tr>
</thead>
<tbody>
{Array(max_rows)
.fill(0)
.map((key, index) => (
<tr key={index}>
{keys.map((item, ind) => (
<td key={ind}>
<div className="column">
{arr[0][item][index] ? (
<div className="option">
{arr[0][item][index]._id}
</div>
) : null}
</div>
</td>
))}
</tr>
))}
</tbody>
</table>
这是一个沙盒:https://codesandbox.io/s/adoring-wave-5fub7?file=/src/App.js