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",
}]
}
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);
}
How can I create one for loop that can read through both (or multiple) categories?
Here is my working example in this JSFiddle: https://jsfiddle.net/dsk1279b/1
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…