I am populating a html table with data from the JSON file. It currently populates the table with all the data in the order its displayed in the json file, however I want it to group the data in different tables based on the "group" category in the file. How would I make it sort by group "entree, starter, salad etc"
Script File:
let http = new XMLHttpRequest();
http.open('get', 'products.json', true);
http.send();
http.onload = function(){
if(this.readyState == 4 && this.status == 200){
let products = JSON.parse(this.responseText);
let output = "";
for(let item of products){
output += `
<div class="product">
<img src="${item.image}" alt="${item.description}">
<p class="title">${item.title}</p>
<p class="description">${item.description}</p>
<p class="price">
<span>$${item.price}</span>
</p>
</div>
`;
}
document.querySelector(".products").innerHTML = output;
}
}
JSON File
{
"image": "products/01.jpg",
"title": "Hamburger",
"description": "Double Bacon Cheeseburger with Fries",
"price": "9.99",
"group": "Entree"
},
{
"image": "products/02.jpg",
"title": "French Fries",
"description": "Large Fries servered with ketchup and aioli",
"price": "4.99",
"group": "Starter"
},
{
"image": "products/03.jpg",
"title": "Hot Dog",
"description": "Loaded Hot Dog with side of fries",
"price": "6.99",
"group": "Entree"
},
{
"image": "products/04.jpg",
"title": "Caesar Salad",
"description": "Small Side Caesar Salad",
"price": "7.99",
"group": "Salad"
}
HTML
<body>
<h2>Joes Diner - Dinner Menu</h2>
<div class="products"></div>
<script src="script.js"></script> <!-- link to the javascript file -->
</body>
2
Answers
Hope this is your expected result, Here I’m grouping products based on their
"group"
and then louping over each group and creating a HTML table for it.The script below will filter
arr
for the appropriate course and abd will present them in the order given incourses
: