Search code examples
javascriptvariableshandlebars.jshandlebarshelper

Displaying data using handlebars based on javascript variable values


I have a handlebar data structure which is in this form

    var data = [{
    "flightno": "F10001",
    "dept_time": "2100",
    "travel_time": "13.05",
    "origin": "Sydney",
    "destination": "Delhi",
    "infant": "No",
    "recliner": "No",
    "Premium": "1",
    "Economy": "2",
    "Business": "3"
}];

And i am getting the origin and destination into javascript variable through a form. Now i need to display data from the handlebars array that contains the corresponding values to those js variables.

To further clarify if i have 2 js variables with an origin and destination values respectively , i need to search the data array for those origin and destination and then display all of the attributes using each helper .

{{#each this}}
<tr>
<td><input type="radio" name="chosenflight" value="{{flightno}}"></td>
<td>{{flightno}}</td>
<td>{{dept_time}}</td>
<td>{{formatTravelTime travel_time}}</td>
<td>{{Premium}}</td>
<td>{{Economy}}</td>
<td>{{Business}}</td>
</tr>
{{/each}}

Solution

  • If I understand the question correctly, you need to filter your array before passing it to handlebars. You can do it using javascript Like

     var origin = "Sydney";
     var dest = "Delhi";
    
     var modData = data.filter(function(obj) {
         return obj.origin.toLowerCase() === origin.toLowerCase() && obj.destination.toLowerCase() === dest.toLowerCase();
     });
    
     console.log(modData);