Access nested objects

会有一股神秘感。 提交于 2019-12-11 13:32:08

问题


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>

回答1:


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>



回答2:


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);
  
});


来源:https://stackoverflow.com/questions/34485768/access-nested-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!