Search code examples
javascriptjqueryjsonmustache

How to render dynamic generated key in mustache


I have a json data with fields. I want to render it in mustache js. But the problem is one of the item in the list is generating dynamically. How can I iterate this item.

I used the given code

 '{{#view}}{{#.}}<td class="number">{{.}}</td>{{/.}}{{/view}}' +
 '{{#comment}}{{#.}}<td class="number">{{.}}</td>{{/.}}{{/comment}}' +
 '{{#rating}}{{#.}}<td class="number">{{.}}</td>{{/.}}{{/rating}}' +

But it rendering as [object object]

Json array format

How can I solve this issue?


Solution

  • The . is only for iterating through an array of strings, so your template will not work. However, you can always process/modify your data before parsing it to the template:

    for (key in data){
      if (key == 'comment' || key == 'rating' || key == 'view'){
         //Turn it into an array
         var temp_array = [];
         for (key2 in data[key]){
           // To make sure it is not a function or __proto__ object whatsoever
           if (typeof data[key][key2] != "object" && typeof data[key][key2] != "function") {
             temp_array.push(data[key][key2]);
           }
         }
         data[key] = temp_array;
      }
    }
    

    To change the item list into an array and then parse to the template.

    Hope this help.