访问嵌套对象

Access nested objects

我正在尝试访问主条目中的嵌套成分对象。 {{recipe.ingredients}} 标签的输出是 [object Object],[object Object]。我需要输入什么才能让 {{recipe.ingredients}} 输出名称和金额?

来自数据库的对象

{
  "_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
}

代码

<template name="RecipeSingle">
  <h1>{{recipe.name}}</h1>
  <p>{{recipe.desc}}</p>
  <p>{{recipe.ingredients}}</p>
</template>
recipe.ingredients[0].name // Will output Bread
recipe.ingredients[1].name // Will output 2 Slices

ingredients 是一个数组,迭代它可能会给你所有的 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);
  
});

由于ingredients 是一个对象数组,您将需要使用流星集合语法来呈现项目集。正如@Félix Saparelli 在评论中提到的,有一个很好的例子 here。例如:

<div class="RecipeList">
    <ul>
        {{#each recipe.ingredients}}
        <li>
            <h1>{{name}}</h1>
            <p>{{amount}}</p>
        </li>
        {{/each}}
    </ul>
</div>