遍历JSON数据以生成HTML [英] Looping through JSON Data to Generate HTML
问题描述
我有如下所示的JSON数据:
I have JSON data that looks like this:
data = {
"tennis": [{
"Description": "Insert description here.",
"Price": 379.99,
"ProductName": "Babolat Play Pure Drive",
}, {
"Description": "Insert description here.",
"Price": 199.99,
"ProductName": "Yonex AI 98 Tennis Racquet",
}],
"basketball": [{
"Description": "Insert description here.",
"Price": 64.99,
"ProductName": "Wilson NCAA Solution Official Game Basketball",
}, {
"Description": "Insert description here.",
"Price": 59.99,
"ProductName": "Spalding NBA NeverFlat Size 7 Composite Leather Basketball",
}]
}
我正在使用此数据生成HTML,因此它的格式正确,易于用户阅读.我这样做的方法是创建一个for循环以阅读网球和篮球类别.例如:
I am using this data to generate HTML so it looks properly formatted and easily readable for the user. The way I am doing this is by creating a for loop to read through tennis and basketball categories. For example:
for (var i = 0; i < data.tennis.length; i++) {
tennisProducts.push(data.tennis[i]);
var tennisProductsTitle = tennisProducts[i].ProductName;
var tennisProductsDescription = tennisProducts[i].Description;
var tennisProductsPrice = tennisProducts[i].Price;
var badge = document.createElement('div');
badge.className = 'badge';
badge.innerHTML =
'<h1>' + tennisProductsTitle + '</h1>' +
'<h2>' + tennisProductsDescription + '</h1>' +
'<div class="options-only-phone">' +
'<a class="service-provider-call" href="#" target="_blank"> Buy for $' + tennisProductsPrice + '</a>';
document.getElementById('tennis-products-list').appendChild(badge);
}
如何创建一个可以读取两个(或多个)类别的for循环?
How can I create one for loop that can read through both (or multiple) categories?
这是我在此JSFiddle中的工作示例: https://jsfiddle.net/dsk1279b/1
Here is my working example in this JSFiddle: https://jsfiddle.net/dsk1279b/1
推荐答案
双循环,一个循环对象的属性,另一个循环数组:
Double loop, one to iterate the object properties, the next to iterate the array:
for (var key in data) {
for (var i = 0; i < data[key].length; i++) {
//HTML logic
}
}
您的小提琴已更新: https://jsfiddle.net/dsk1279b/4/
最终代码:
for (var key in data) {
for (var i = 0; i < data[key].length; i++) {
var title = data[key][i].ProductName;
var desc = data[key][i].Description;
var price = data[key][i].Price;
var badge = document.createElement('div');
badge.className = 'badge';
badge.innerHTML =
'<h1>' + title + '</h1>' +
'<h2>' + desc + '</h1>' +
'<div class="options-only-phone">' +
'<a class="service-provider-call" href="#" target="_blank"> Buy for $' + price + '</a>';
//I gave the div the same ID's as the keys in the object for ease
document.getElementById(key).appendChild(badge);
}
}
这篇关于遍历JSON数据以生成HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!