Search code examples
javascriptejshtml-templates

Javascript loop for HTML template


I am building a list of items using a single JSON where several items have a common key:value pair and are sorted and clubbed together. The need is to make a header above the clubbed section using the common valued key-value pair. And then wrap the list items as per groups with the heading between group.

While most of the logic is written, the only thing that I am unable to implement is the closing DIV for the clubbed section .table-wrp.

This is the link to the codepen: https://codepen.io/nitinsuri/pen/OJgbXZN.

Any help will be highly appreciated.


Solution

  • I ended up recreating this with my own vision of what it 'should' look like (and apologies for the poor styling).

    My main additions are as follows.

    1. Getting a unique array of regions, since that is how we plan on segregating the array of items.
    const uniqueRegions = [...new Set(bridgesListData.map(({region})=>region))].sort()
    
    1. Next, based on the region you are in, you can retrieve the relevant items:
    const itemsByRegion = (array, region) => {
      return bridgesListData.filter((item)=>item.region === region)
    }
    

    Simply pass the function expression the array and region in question and you will have the items you want.

    1. Although it needs some styling help, the table can be displayed using a couple of forEach loops (I really don't like using a for loop because of how much additional complexities (vs benefits) it introduces.
    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>
     <%}) %>`;
    
    

    I hope I understood your requirements here.