0

I'm trying to create a table from data that I get from querying a mongoDB. The data has the following structure:

[
  { team_shortName: 'Liverpool', position: 1, overall_points: 99 },
  { team_shortName: 'Man City', position: 2, overall_points: 81 },
  { team_shortName: 'Chelsea', position: 4, overall_points: 66 },
  { team_shortName: 'Leicester', position: 5, overall_points: 62 },
  { team_shortName: 'Man Utd', position: 3, overall_points: 66 },
]

I want to use the keys in the array as headers for the table, but can't figure out how to access and display them using handlebars. Here is how I want my table to look like

  <table class="bordered highlight centered" style="border: 1px solid black">
    <thead>
      <tr>
         <th>{{ #DISPLAY HEADERS }}</th>
      </tr>
    </thead>
    <tbody>
        {{#each result}}
            <tr>
                <td>{{this.team_shortName}}</td>
                <td>{{this.position}}</td>
                <td>{{this.overall_points}}</td>
            </tr>
        {{/each}}
    </tbody>
</table>

rendered table would look like this

team_shortName    position   overall_points
Liverpool           1             99
Man City            2             81
Chealsea            4             66
Leicester           5             62
Man Utd             4             66
MisterButter
  • 749
  • 1
  • 10
  • 27
  • Does this answer your question? [Handlebars/Mustache - Is there a built in way to loop through the properties of an object?](https://stackoverflow.com/questions/9058774/handlebars-mustache-is-there-a-built-in-way-to-loop-through-the-properties-of) – Lionel Rowe Oct 04 '20 at 22:16
  • @LionelRowe Not really as I do not want to loop through the array as that will result in the headers being displayed as many times as there are objects in the array. – MisterButter Oct 04 '20 at 22:18
  • Based on the accepted answer, `#each` used on an object loops though its properties, within which you can get the key with `@key`. – Lionel Rowe Oct 04 '20 at 22:26
  • Thank you for the input, your suggestion jogged my mind and I manage to solve it by first using `#with` and later `#each` to get the `@key`. – MisterButter Oct 04 '20 at 22:31
  • I believe your question is similar to this one: https://stackoverflow.com/q/47809752/3397771 – 76484 Oct 05 '20 at 00:52

1 Answers1

0
  <table class="bordered highlight centered" style="border: 1px solid black">
    <thead>
      <tr>
        {{#with result.[0]}}
            {{#each .}}
                <th>{{ @key  }}</th>
            {{/each}}
        {{/with}}

      </tr>
    </thead>
    <tbody>
        {{#each result}}
            <tr>
                <td>{{this.team_shortName}}</td>
                <td>{{this.position}}</td>
                <td>{{this.overall_points}}</td>
            </tr>
        {{/each}}
    </tbody>
</table>
MisterButter
  • 749
  • 1
  • 10
  • 27