首页 > 解决方案 > HTML模板的Javascript循环

问题描述

我正在使用单个项目构建一个项目列表,JSON其中几个项目有一个共同的key:value对并且被分类和组合在一起。需要使用公共值键值对在棒状部分上方制作标题。然后将列表项按照组与组之间的标题包装起来。

虽然大部分逻辑都已编写,但我唯一无法实现的是关闭DIV棒状部分.table-wrp

这是 codepen 的链接:https ://codepen.io/nitinsuri/pen/OJgbXZN 。

任何帮助将不胜感激。

标签: javascriptejshtml-templates

解决方案


我最终用我自己对它“应该”是什么样子的看法重新创建了这个(并为糟糕的造型道歉)。

我的主要补充如下。

  1. 获得一个独特的区域数组,因为这就是我们计划隔离项目数组的方式。
const uniqueRegions = [...new Set(bridgesListData.map(({region})=>region))].sort()
  1. 接下来,根据您所在的区域,您可以检索相关项目:
const itemsByRegion = (array, region) => {
  return bridgesListData.filter((item)=>item.region === region)
}

只需将函数表达式传递给相关数组和区域,您就会拥有所需的项目。

  1. 虽然它需要一些样式帮助,但可以使用几个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>
 <%}) %>`;

我希望我在这里了解您的要求。


推荐阅读