meteorspacebars

meteor:How do I iterate over an array of objects when property name is not known


I have an array of objects over which I have to iterate, but I don't know the property name of object.

{{# each }}

{{??}} {{/each}}


Solution

  • Break it down into two #eachs. The outer #each loops over the array of objects. The inner #each calls a template helper that returns an array of objects with label and value of each property of that object.

    The template:

    {{#each arrayOfObjects}}
      {{#each getAllFields}}
         <div class="item">
            {{this.label}} <span class="field-value">{{this.value}}</span>
         </div>
      {{/each}}
    {{/each}}
    

    The helper:

    getAllFields: function() {
        let fields = [];
        const unknownObject = this;
    
        _.each(Object.keys(unknownObject), function(theKey) {
            fields.push({label: theKey, value: unknownObject[theKey] });
        });
    
        fields = _.sortBy(fields, 'label');
        return fields;
    }