列出 blaze 对象的所有键和值

List all keys and values of blaze object

我已将此数据插入 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 对象的 key/value 对。

之所以这样,是因为我不知道 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}} 给出了一个对象。

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

您正在生成一个数组数组(每个目录项映射到 key/value 对的列表)。一种解决方案是遍历每个目录项,然后对其调用 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}}