dpatnaik
dpatnaik

Reputation: 188

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}}

Upvotes: 1

Views: 284

Answers (1)

Travis White
Travis White

Reputation: 1977

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;
}

Upvotes: 1

Related Questions