0

I have been trying and failing to iterate through some JSON Data with Mustache JS in order to populate a table which looks like:

{
   "Pay":[
      [
         "Regular Hours",
         "$75.00",
         "$75.00"
      ]
   ],
   "Earnings":[
      [
         "Regular Earnings",
         "$2,277.00",
         "$1,200.00"
      ],
      [
         "Non Tax Vacation Pay",
         "$0.00",
         "$50.80"
      ]
   ],
   "Deductions":[
      [
         "Other Deduction 5",
         "$0.00",
         "$50.00"
      ]
   ]
}

How would I iterate using Mustache JS in order to have every inner array as rows and the outer array as headers like this:

<tr>
   <th colspan="4">Pay</th>
</tr>
<tr>
   <td>Regular Hours</td>
   <td>75</td>
   <td>75</td>
</tr>

<!-- Etc. -->

Any help would be greatly appreciated

David Pullar
  • 696
  • 6
  • 18

1 Answers1

0

This issue has made me consider switching over to handlebars to avoid the need for hacky code. The data being passed in is the JSON input from the original question. This function will format the data into key value pairs, after which the data is rendered by the Mustache template.

function (data) {
    var payslipList = JSON.parse(data.d);
    formattedData = { 'entries': [] };
    for (var property in payslipList) {
        if (payslipList.hasOwnProperty(property)) {
            formattedData['entries'].push({
            'key': property,
            'value': payslipList[property]
        });
    }
}

var tablePayslip = $("#tblPayDetails tbody");
$.each(formattedData, function (id, payslip) {
    var template = $('#renderPaystub').html();
    var html = Mustache.render(template, payslip);
    tablePayslip.append(html);
});

The template to access the key value pairs would look something like this:

<script type="text/template" id="renderPaystub">
    {{#.}}
        {{#.}}
            <tr>
                <th colspan="3">{{key}}</th>
            </tr>
         {{/.}}
         {{#value}}
             <tr>
                 {{#.}}<td>{{.}}</td>{{/.}}
             </tr>
         {{/value}}
    {{/.}}
</script>

This template is fairly ugly and ambiguous, if there is a better method to achieve this, feel free to let me know.

David Pullar
  • 696
  • 6
  • 18