Iterating through an array using spaces

This is part two of my last question . Thanks to some helpful people, I now have a document that looks like this:

{ "_id" : "dndsZhRgbPK24n5LD", "createdAt" : ISODate("2014-11-26T16:28:02.655Z"), "data" : { "cat1" : 493.6, "cat2" : 740.4 }, "owner" : "GiWCb8jXbPfzyc5ZF", "text" : "asdf" }

      

Specifically, I want to extract the value from each property data

in Spacebars and iterate over it to create a table - and I know the number of fields in the object data

, but the number can change. Yes, I know it was before , but no one seems to have been able to provide a satisfactory answer that works. But as the end result, I would like to display the whole document in a row, like

<tbody>
  <tr>
    <td>493.6</td>
    <td>740.4</td>
    <td>asdf</td>
</tbody>

      

Thanks in advance for your help.

+3


source to share


1 answer


Here's a complete working example:

Cats = new Mongo.Collection(null);

Meteor.startup(function() {
  Cats.insert({
    data: {
      cat1: 100,
      cat2: 200
    },
    text: 'cat1'
  });

  Cats.insert({
    data: {
      cat1: 300,
      cat2: 400,
      cat3: 500
    },
    text: 'cat2'
  });
});

Template.cats.helpers({
  cats: function() {
    return Cats.find();
  },

  // Returns an array containg numbers from a cat data values AND the cat's
  // text. For example if the current cat (this) was:
  // {text: 'meow', data: {cat1: 100, cat2: 300}}, columns should return:
  // [100, 200, 'meow'].
  columns: function() {
    // The current context (this) is a cat document. First we'll extract an
    // array of numbers from this.data using underscore values function:
    var result = _.values(this.data);

    // result should now look like [100, 200] (using the example above). Next we
    // will append this.text to the end of the result:
    result.push(this.text);

    // Return the result - it shold now look like: [100, 200, 'meow'].
    return result;
  }
});

      



<body>
  {{> cats}}
</body>

<template name='cats'>
  <table>
    {{#each cats}}
      <tr>
        {{#each columns}}
          <td>{{this}}</td>
        {{/each}}
      </tr>
    {{/each}}
  </table>
</template>

      

+5


source







All Articles