javascript - HTML模板的Javascript循环
问题描述
我正在使用单个项目构建一个项目列表,JSON
其中几个项目有一个共同的key:value
对并且被分类和组合在一起。需要使用公共值键值对在棒状部分上方制作标题。然后将列表项按照组与组之间的标题包装起来。
虽然大部分逻辑都已编写,但我唯一无法实现的是关闭DIV
棒状部分.table-wrp
。
这是 codepen 的链接:https ://codepen.io/nitinsuri/pen/OJgbXZN 。
任何帮助将不胜感激。
解决方案
我最终用我自己对它“应该”是什么样子的看法重新创建了这个(并为糟糕的造型道歉)。
我的主要补充如下。
- 获得一个独特的区域数组,因为这就是我们计划隔离项目数组的方式。
const uniqueRegions = [...new Set(bridgesListData.map(({region})=>region))].sort()
- 接下来,根据您所在的区域,您可以检索相关项目:
const itemsByRegion = (array, region) => {
return bridgesListData.filter((item)=>item.region === region)
}
只需将函数表达式传递给相关数组和区域,您就会拥有所需的项目。
- 虽然它需要一些样式帮助,但可以使用几个
forEach
循环来显示表格(我真的不喜欢使用for
循环,因为它引入了多少额外的复杂性(相对于好处)。
let template = `<% uniqueRegions.forEach(region => {
%>
<h1><%= region %></h1>
<table>
<thead>
<tr>
<th style="border-bottom: solid 1px black;">Truss Type</th>
<th style="border-bottom: solid 1px black;">Location</th>
<th style="border-bottom: solid 1px black;">Year</th>
</tr>
<thead>
<tbody>
<% itemsByRegion(bridgesListData, region).forEach(item => {
%>
<tr>
<th><%= item.trussType %></th>
<th><%= item.nameLocation %></th>
<th><%= item.year %></th>
</tr> <%
}) %>
</tbody>
</table>
<%}) %>`;
我希望我在这里了解您的要求。
推荐阅读
- python - Pytesseract - 图像上的 OCR,带有不同颜色的文本
- regex - 如何编写 SED 脚本以使用正则表达式根据用户输入替换文件中存在的版本代码
- javascript - 在另一台机器上启动反应应用程序
- coq - 错误“战术失败:关系 (fun xy : BloodType => x <> y) 不是声明的自反关系。” 在证明关于函数的定理时
- architecture - 消息持久化系统设计题
- angular - 如何通过 IP 地址访问 API
- python - ValueError:无法将 DataFrame 与类型的实例合并
- python - win10如何卸载python包
- python - 尝试通过同一本地网络中的网络服务器发布源自本地网络 (RPI) 计算机的视频流
- swift - 使用自定义部分和单元格 Swift 滚动到底部 TableView