【发布时间】:2020-05-30 01:32:30
【问题描述】:
我想动态填充矩阵表。我有这部分 API 响应:
"Characteristics": [
{
"Description": "Benefits - Pay Related",
"Years": [
2018,
2017,
2016
]
},
{
"Description": "Benefits - Preapproved",
"Years": [
2018,
2017,
2016
]
},
{
"Description": "Benefits - Age/Service Weighted Plan",
"Years": [
2018,
2017
]
},
{
"Description": "Benefits - Profit Sharing",
"Years": [
2018,
2017,
2016
]
},
{
"Description": "Benefits - 404c",
"Years": [
2018,
2017,
2016
]
},
{
"Description": "Benefits - Participant Directed",
"Years": [
2018,
2017,
2016
]
},
{
"Description": "Benefits - 401(K)",
"Years": [
2018,
2017
]
},
{
"Description": "Benefits - 401(m) Arrangement",
"Years": [
2018,
2017,
2016
]
},
{
"Description": "Benefits - Auto Enrollment",
"Years": [
2018,
2017
]
}
如您所见,“描述”始终存在,但并非一直存在。最后我想要呈现这样的东西:
提供的表格与数据无关 - 正如您在“福利 - 年龄/服务加权计划”中看到的那样,“年”中没有 2016,所以我希望有“N”。我具有从包含提供任何信息的所有年份的数据的其他部分中检测独特年份的功能。这是在 API 响应中:
const uniqueYearsPension = data => {
return data.map(element => {
return element.Year;
});
};
我尝试像这样填充表格:
<table className="table table-striped table-bordered table-sm table-hover">
<thead className="thead-dark">
<tr>
<th>Description</th>
{DataExtract.uniqueYearsPension(
props.types[2][index]
).map((el, ind) => {
return <th key={ind}>{el}</th>;
})}
</tr>
</thead>
<tbody className="table-hover">
{element.Characteristics &&
element.Characteristics.map((e, i) => {
return (
<tr key={i}>
<td>{e.Description}</td>
{e.Years.reverse().map((year, yearID) => {
console.log(year);
return DataExtract.uniqueYearsPension(
props.types[2][index]
).map((el, ind) => {
console.log(year);
if (year == el) {
return <td key={yearID}>Y</td>;
}
});
})}
</tr>
);
})}
</tbody>
</table>
但它是按 1 填充第 1 行,如果缺少 2016 年,它会将 2017 年的结果放在此列中,因此 2018 年是空的,而不是 2016 年 - 这是绝对正常的。如果我在这里添加 else 语句:
if (year == el) {
return <td key={yearID}>Y</td>;
} else return <td key={yearID}>N</td>
它在行上打印许多许多结果。任何想法如何像矩阵一样填充我的表格?
【问题讨论】:
标签: javascript arrays reactjs jsx