迭代JSON对象并将元素打印到屏幕上的最佳方式是什么

What is the best way to iterate through a JSON object and print elements to the screen?

本文关键字:屏幕 最佳 是什么 方式 打印 对象 JSON 元素 迭代      更新时间:2024-02-24

我只是想学习操作JSON数据并将其显示在屏幕上的最有效方法。我是个笨蛋,所以如果可以的话,尽量把你的答案分解清楚。欢迎使用Javascript和jQuery解决方案。类似这样的东西:


  • 纽约大道20.00美元
  • 罗纹鞋$19.00

蔬菜

  • Kale$4.00
  • Sunchokes$3.20

这是JSON对象(可以更有效地重写吗?):

var foods = { 
   "category":{
       "Meats":[
           {
              "product":"NY Strip",
              "price":20.00,
              "cost":14.00,
              "total sold": 3
           },
           {
              "product":"Ribeye",
              "price":20.00,
              "cost":14.00,
              "total sold": 6
           }
       ],
       "Vegetables":[
           {
              "product":"Kale",
              "price":4.00,
              "cost":2.00,
              "total sold": 10
           },
           {
              "product":"Sunchokes",
              "price":3.20,
              "cost":1.00,
              "total sold": 5
           }
       ]
    }
}

这是我的尝试:(希望我知道一种将类别标题合并到循环中的方法,而不是对它们进行硬编码。)

<h3>Meats</h3>
<script>
    for(key in foods.category.Meats){
       document.write("<li>" + foods.category.Meats[key].product + " $" + foods.category.Meats[key].price + "</li>"); 
    }
</script>
<h3>Vegetables</h3>
<script>
    for(key in foods.category.Vegetables){
       document.write("<li>" + foods.category.Vegetables[key].product + " $" + foods.category.Vegetables[key].price + "</li>"); 
    }
</script>

这将遍历整个对象。

var category = foods.category
for(var cat in category) {
  if(category.hasOwnProperty(cat)) {
    category[cat].forEach(function(item) {
      console.log(item);
      // Do stuff here
    });
  }
}

这里有另一种方法:

Object.keys(foods.category).forEach(function(category) {
    foods.category[category].forEach(function(item) {
       console.log('do stuff with', item);
    });
});

啊,谢谢大家。

var category = foods.category
        for(var key in category) {
          if(category.hasOwnProperty(key)) {
            category[key].forEach(function(item) {
                if(document.getElementById(key) === null){
                    document.write("<h4" + " id='" + key + "'" + ">" + key + "</h4>")
                }
              document.write("<li>" + item.product + "</li>");
            });
          }
        }