【发布时间】:2020-04-20 13:52:26
【问题描述】:
我有一个嵌套的 JSON,我正试图将它呈现到一个表中。这个想法是通过遍历 JSON 来填充。我的问题是当我迭代 Tags 并尝试填充环境列时。如果键存在,它可以正常工作,但如果键不存在,它会将 TD 转移到前一列。
例如,在下图中,您可以在第一行看到 web 到 ENV 列,而不是 Purpose 列。对于其他两个,由于键存在,因此表格呈现良好。
import React, { Component } from "react";
import { Table } from "reactstrap";
class Example extends Component {
state = {
data: [
{
id: "1",
States: "many",
Purpose: "web",
Tags: [
{
Key: "Name",
Value: "server1"
}
]
},
{
id: "2",
States: "Single",
Purpose: "App",
Tags: [
{
Key: "Name",
Value: "server2"
},
{
Key: "env",
Value: "qa"
}
]
},
{
id: "3",
States: "None",
Purpose: "DB",
Tags: [
{
Key: "env",
Value: "qa"
},
{
Key: "Name",
Value: "server3"
}
]
}
]
};
render() {
let envs;
return (
<Table className="align-items-center table-flush" responsive>
<thead className="thead-light">
<tr>
<th scope="col">ID</th>
<th scope="col">States</th>
<th scope="col">Env</th>
<th scope="col">Purpose</th>
</tr>
</thead>
<tbody>
{this.state.data.map(info => (
<tr>
<th scope="row">{info.id}</th>
<td>{info.States}</td>
{info.Tags.filter(env => env.Key === "env").map(e => (
<td>{e.Value}</td>
))}
<td>{info.Purpose}</td>
</tr>
))}
</tbody>
</Table>
);
}
}
export default Example;
【问题讨论】:
标签: arrays json reactjs datatable nested