用空格键遍历数组 [英] Iterating through an array with Spacebars

查看:41
本文介绍了用空格键遍历数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我最后一个问题的第 2 部分.感谢一些乐于助人的人,我现在有一个看起来像这样的文档:

This is somewhat of a part 2 to my last question. Thanks to some helpful folks, 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" }

具体来说,我想从空格键中 data 的每个属性中提取值并对其进行迭代以创建一个表 - 我知道对象 data 但数量可能会有所不同.是的,我知道这已经之前问过,但似乎没有人能够给出令人满意的答案.但作为最终结果,我想连续显示整个文档,就像这样

Specifically, I want to extract the value from each property of data in Spacebars and iterate over it to create a table - and I know the number of fields in object data but the number can vary. Yes, I know this has been asked before but nobody has seemed to be able to give a satisfactory answer that works. But as a final result I would like to display the whole document in a row, like this

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

在此先感谢您的帮助.

推荐答案

以下是完整的工作示例:

Here's 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's 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's 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>

这篇关于用空格键遍历数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆