2014-11-23 53 views
0

我有以下的JSON:遍歷JSON和顯示項目的具體名稱

{ "Food" : [ { "Meat" : "beef lamb turkey", 
       "Vegetables" : "broccoli potatoes carrots", 
       "Fruit" : "apples bananas strawberries", 
       "Sugar" : "candy softdrinks", 
       "Dairy" : "milk cheese yoghurt", 
       "Grains" : "wheat barley rice", 
       "Fat" : "fries KFC", 
      }, 
] 

我通過這個嘗試循環,而只顯示「糖」和「發」的項目。

我有這樣的:

<script type="text/html" id="badFoods"> 
    <div> 
     <% _.each(container.Food, function(food, i) {%> 
      display the name here i.e Sugar and Fat 
     </div> 
     <% }); %> 
    </div> 
</script> 

當我運行此,我希望它顯示如下:

糖:糖軟飲料 脂肪:薯條肯德基

道歉,這可能是有點模糊,只是爲了尋找在正確的方向一推,所以我可以讓我的頭解決這個問題。

謝謝!

回答

0
#1 
<% _.each(container.Food, function(food, key) {%> 
    Sugar: <%= food.Sugar %> Fat: <%= food.Fat %> 
<% }); %> 

#2 
<% _.each(container.Food, function(food, key) { %> 
    <% _.each(food, function(value, key) { %> 
    <% if (key === 'Sugar' || key === 'Fat') { %> 
     <%= key %>: <%= value %> 
    <% } %>   
    <% }); %> 
<% }); %>