【问题标题】:Loop through JSON and display items with specific names遍历 JSON 并显示具有特定名称的项目
【发布时间】:2014-11-23 13:47:18
【问题描述】:

我有以下 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>

当我运行它时,我希望它显示以下内容:

糖:糖果软饮料 脂肪:炸薯条肯德基

抱歉,这可能有点含糊,只是在寻找正确方向的推动力,以便我能解决这个问题。

谢谢!

【问题讨论】:

    标签: javascript html json loops


    【解决方案1】:
    #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 %> 
        <% } %>          
      <% }); %>
    <% }); %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-01
      • 1970-01-01
      • 2012-06-25
      相关资源
      最近更新 更多