skip to Main Content

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


  1. 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.

    http.onload = function(){
        if(this.readyState == 4 && this.status == 200){
    
            let products = JSON.parse(this.responseText);
            
            let groupedProducts = {};
            products.forEach(item => {
                if (!groupedProducts[item.group]) {
                    groupedProducts[item.group] = [];
                }
                groupedProducts[item.group].push(item);
            });
    
            let output = "";
            
            for (let group in groupedProducts) {
                output += `<h3>${group}</h3><table>`;
                groupedProducts[group].forEach(item => {
                    output += `
                        <tr>
                            <td><img src="${item.image}" alt="${item.description}"></td>
                            <td class="title">${item.title}</td>
                            <td class="description">${item.description}</td>
                            <td class="price">$${item.price}</td>
                        </tr>
                    `;
                });
                output += "</table>";
            }
    
            document.querySelector(".products").innerHTML = output;
        }
    }
    
    Login or Signup to reply.
  2. The script below will filter arr for the appropriate course and abd will present them in the order given in courses:

    const arr=[{"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"}], 
    courses = {
      Entree: [],
      Starter: [],
      Salad: []
    };
    
    // filter for existing courses and add meal to the appropriate course:
    arr.forEach(m => courses[m.group] && courses[m.group].push(m));
    
    document.querySelector(".products").innerHTML =
      Object.entries(courses).map(([course, marr]) => `<h3>${course}</h3>` +
        marr.map(item => `<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>`).join("n")).join("n");
    <body>
      <h2>Joes Diner - Dinner Menu</h2>
      <div class="products"></div>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search