gpt4 book ai didi

javascript - 循环数组并填充矩阵 - JS

转载 作者:行者123 更新时间:2023-12-02 21:47:18 27 4
gpt4 key购买 nike

我想动态填充矩阵表。我有这部分 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
]
}

如您所见,“描述”始终存在,但并非所有年份都存在。最后我想要呈现这样的东西:

enter image description here

提供的表格与数据无关 - 正如您在“福利 - 年龄/服务加权计划”中看到的那样,“年份”中没有 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>

它正在行上打印许多结果。有什么想法如何像矩阵一样填充我的表格吗?

最佳答案

首先尝试将uniqueYearsPension的结果保存到变量中以避免重新计算。然后在渲染期间 tr 只需映射所有年份并检查 e.Years 是否包含该值。代码如下所示:

const uniqueYears = DataExtract.uniqueYearsPension(props.types[2][index]);
...
...
<table className="table table-striped table-bordered table-sm table-hover">
<thead className="thead-dark">
<tr>
<th>Description</th>
{
uniqueYears.map((value, key) => {
return <th key={key}>{value}</th>;
})
}
</tr>
</thead>
<tbody className="table-hover">
{element.Characteristics &&
element.Characteristics.map((e, i) => {
return (
<tr key={i}>
<td>{e.Description}</td>
{
uniqueYears.map((year, yearID) => {
if (e.Years.includes(year)) {
return <td key={yearID}>Y</td>;
} else {
return <td key={yearID}>N</td>;
}
})
}
</tr>
);
})}
</tbody>
</table>

关于javascript - 循环数组并填充矩阵 - JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60223126/

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