Javascript 循环 HTML 模板

Javascript loop for HTML template

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

虽然写了大部分逻辑,但我唯一无法实现的是俱乐部部分.table-wrp的结束DIV

这是代码笔的 link:https://codepen.io/nitinsuri/pen/OJgbXZN

任何帮助将不胜感激。

我最终根据自己对 'should' 外观的看法重新创建了它(并对糟糕的样式表示歉意)。

我的主要补充如下

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

只需将有问题的数组和区域传递给函数表达式,您就会得到想要的项目。

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

希望我理解了您的要求here