Access nested objects

2019-08-08 23:07发布

I'm trying to access the nested ingredients object within the main entry. The output from the {{recipe.ingredients}} tag is [object Object],[object Object]. What do I need to put in order for the {{recipe.ingredients}} to output the name and amount?

Object from a database

{
  "_id": "zSetYKmvv2HB6v8hJ",
  "name": "Grilled Cheese",
  "desc": "Sandwich",
  "ingredients": [{
    "name": "Bread",
    "amount": "2 Slices"
  }, {
    "name": "Cheese",
    "amount": "Lots"
  }],
  "author": "ttpbGPgzDnqwN8Gg7",
  "createdAt": "2015-12-27T22:53:17.729Z",
  "inMenu": false
}

Code

<template name="RecipeSingle">
  <h1>{{recipe.name}}</h1>
  <p>{{recipe.desc}}</p>
  <p>{{recipe.ingredients}}</p>
</template>

2条回答
Evening l夕情丶
2楼-- · 2019-08-08 23:52
recipe.ingredients[0].name // Will output Bread
recipe.ingredients[1].name // Will output 2 Slices

ingredients is an array, and probably iterating over it will give you all the ingrident's name and amount.

var recipe = {
  "_id": "zSetYKmvv2HB6v8hJ",
  "name": "Grilled Cheese",
  "desc": "Sandwich",
  "ingredients": [{
    "name": "Bread",
    "amount": "2 Slices"
  }, {
    "name": "Cheese",
    "amount": "Lots"
  }],
  "author": "ttpbGPgzDnqwN8Gg7",
  "createdAt": "2015-12-27T22:53:17.729Z",
  "inMenu": false
};

recipe.ingredients.forEach(function(el, i){

  alert("Ingredient "+i+": "+el.name+", "+el.amount);
  
});

查看更多
仙女界的扛把子
3楼-- · 2019-08-08 23:58

As the ingredients are an array of objects, you will need to use meteors collection syntax to render the item set. As @Félix Saparelli mentioned in a comment, there is a good example of that here. For example:

<div class="RecipeList">
    <ul>
        {{#each recipe.ingredients}}
        <li>
            <h1>{{name}}</h1>
            <p>{{amount}}</p>
        </li>
        {{/each}}
    </ul>
</div>
查看更多
登录 后发表回答