【问题标题】:List all keys and values of blaze object列出 blaze 对象的所有键和值
【发布时间】:2016-07-24 08:24:46
【问题描述】:

我已经在 mongo 中插入了这些数据

db.orders.insert( { _id: ObjectId().str, name: "admin", status: "online",catalog : [
        {
            "objectid" : ObjectId().str,
            "message" : "sold",
            "status" : "open"
        }
    ]})

我正在以这种方式访问​​数据

<template name="Listed">
  <div class="row">

    {{#each list}}
  <article class="post">
  <a href="{{pathFor route='edit'}}"><h3>{{_id}}</h3></a>
  <a href="{{pathFor route='edit'}}"><h3>{{name}}</h3></a>
  <br>
  <a href="{{pathFor route='create'}}"><h3>{{status}}</h3></a>
  <br>
  {{#each catalog  }}
  <a href="{{pathFor route='create'}}"><h3></h3></a>
   <a href="{{pathFor route='create'}}"><h3>{{status}}</h3></a>
   {{/each}}
     <div class="well"></div>
     <br/>

    </article>
   <br/><br/>
   {{/each}}
   </div>
</template>

我有兴趣了解catalog 对象的键/值对。

之所以这样,是因为我不知道catalog 的字段。为此,我注册了一个助手

Template.registerHelper("keyval",function(object){
  return _.map(object, function(value, key) {
    return {
      key: key,
      value: value
    };
  });
});

并以这种方式使用它

<template name="Listed">
  <div class="row">

    {{#each list}}
      <article class="post">
      <a href="{{pathFor route='edit'}}"><h3>{{_id}}</h3></a>
      <a href="{{pathFor route='edit'}}"><h3>{{name}}</h3></a>
      <br>
      <a href="{{pathFor route='create'}}"><h3>{{status}}</h3></a>
      <br>
      {{#each keyval catalog  }}
      <a href="{{pathFor route='create'}}"><h3></h3></a>
       <a href="{{pathFor route='create'}}"><h3>{{key}}</h3></a>
       <a href="{{pathFor route='create'}}"><h3>{{value}}</h3></a>
       {{/each}}
     <div class="well"></div>
     <br/>

    </article>
   <br/><br/>
   {{/each}}
   </div>
</template>

当我尝试访问像 {{key}} 这样的密钥时,我得到 0,1,2... 而{{value}} 给出了一个对象。

这不是我想要的。如何正确显示键值对?

【问题讨论】:

  • 问题是你有一个catalog 项目的数组,并且对于每一个你正在生成另一个数组,所以你最终得到一个数组数组而不是单个平面数组。我不清楚输出应该代表原始结构还是只是一个平面列表。
  • 是的,它应该代表原始结构。

标签: javascript meteor handlebars.js meteor-blaze


【解决方案1】:

您正在生成一个数组数组(每个目录项映射到一个键/值对列表)。一种解决方案是遍历每个目录项,然后对其调用keyval。结构看起来像这样:

{{#each item in catalog}}
  {{#each keyval item}}
    <a href="{{pathFor route='create'}}"><h3>{{key}}</h3></a>
    <a href="{{pathFor route='create'}}"><h3>{{value}}</h3></a>
  {{/each}}
{{/each}}

【讨论】:

    猜你喜欢
    • 2020-05-24
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 2020-06-06
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多