我只是想学习操作JSON数据的最有效方法,并将其拍到屏幕上。我是一个菜鸟,所以如果可以的话,尽量清楚地打破你的答案。欢迎使用Javascript和jQuery解决方案。像这样:
肉类
蔬菜
这是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>
答案 0 :(得分:1)
这将遍历整个对象。
var category = foods.category
for(var cat in category) {
if(category.hasOwnProperty(cat)) {
category[cat].forEach(function(item) {
console.log(item);
// Do stuff here
});
}
}
答案 1 :(得分:0)
这是另一种方法:
Object.keys(foods.category).forEach(function(category) {
foods.category[category].forEach(function(item) {
console.log('do stuff with', item);
});
});
答案 2 :(得分:0)
啊,谢谢你们。
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>");
});
}
}