2

I am new to meteor, and am struggling with using #each in blaze. I tried following this answer on stackoverflow, but my requirement is slightly different.

I have a json object array:

{
    "accounting": [{
            "firstName": "John",
            "lastName": "Doe",
            "age": 23
        },

        {
            "firstName": "Mary",
            "lastName": "Smith",
            "age": 32
        },

        {
            "firstName": "Mike",
            "lastName": "Nolan",
            "age": 21
        }
    ]
}

How do I display firstName from each object, using blaze (specifically using #each to iterate the array) in a meteor project.

I tried a lot of different ways, using multiple helper methods, but am not able to make it happen. If someone can please help.

Also, if it is not possible, please tell alternatives to achieve the same.

The data is coming from an API call, and the format of data is a json object, but is stored as a Session variable (so that's where I will be getting it from in the helper method, using Session.get()).

Community
  • 1
  • 1

2 Answers2

2

It's going to depend on where your data is coming from. In my example you can replace my hard-coded variable with the source of your object. If you add where it is coming from I can modify my solution.

Basically, you just return the array of objects inside of the JSON object with a helper function. From there you can call the helper in an #each block, and reference firstName directly with {{firstName}}

Template

<template name="yourTemplateName">
    {{#each accounting}}
        {{firstName}}
    {{/each}}
</template>

Helper

Template.yourTemplateName.helpers({
    accounting: function () {
        var data = Session.get('apiResponse');
         //You return the array of objects, which can then be iterated with each
        if (!_.isEmpty(data)){
            return data.accounting;
        } else {
            return []
        }
     }
});
challett
  • 906
  • 6
  • 16
1

I'm assuming that the API response is in a session variable called apiResponse.

Define a helper as follows:

Template.body.helpers({
  response: function () { 
    return Session.get('apiResponse');
  }
});

In your template, call the response helper with a #with template tag to set a data context and inside this tag iterate over the accounting array using a #each template tag.

<body>
  {{#with response}}
    {{#each accounting}}
      <p>{{firstName}} {{lastName}} is {{age}} years old.</p>
    {{/each}}
  {{/with}}
</body>

You will see this in your browser window -

John Doe is 23 years old.

Mary Smith is 32 years old.

Mike Nolan is 21 years old.
umesh
  • 338
  • 1
  • 6