Search code examples
handlebars.jsmustacheexpress-handlebars

How do I extract out the data from this array of arrays of objects


I am getting out data from a database, and because the database contains more than one recordset, it is ending up with output like this:

 [
      [ { TotalRecords: 11873 } ],
   [
    {
          ProductID: 12394,
          ProductTitle: 'XYZ1'
    },
    {
          ProductID: 14282,
          ProductTitle: 'XYZ2'
    },
    {
          ProductID: 11405,
          ProductTitle: 'XYZ3'
    },
    {
          ProductID: 12467,
          ProductTitle: 'XYZ4'
    }    
  ]
]

I pass all that data to my view (Handlebars) as an object called products. How can I loop around the second array which contains the ProductID and ProductTitle information to display it on a page?


Solution

  • Provided that the position is known, you can iterate over the second array by this:

    {{#each products.[1]}}
      <p>{{ProductID}}: {{ProductTitle}}</p>
    {{/each}}
    

    Note the [1] which specifies the index number.