List all keys and values of blaze object

时间:2016-04-04 17:04:53

标签: javascript meteor handlebars.js meteor-blaze

I have inserted this data in mongo

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

and i am accessing the data this way

<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>

I am interested in knowing the key/value pair of the catalog object.

The reason for this,is because,i do not know the fields catalog has. For that,i registered a helper

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

and used it this way

<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>

When i try to access the key like {{key}} i get 0,1,2... and {{value}} gives an object.

That is not what am looking for. How can i display the key value pairs correctly?.

1 个答案:

答案 0 :(得分:2)

You are producing an array of arrays (each catalog item maps to a list of key/value pairs). One solution is to iterate over each of the catalog items and then call keyval on it. The structure would look something like this:

{{#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}}