Arranging JSON information based on category

I am currently populating an HTML table with data retrieved from a JSON file. It currently displays all the data in the order it appears in the JSON file, but I would like to organize it into different tables based on the "group" category in the file such as entree, starter, salad, etc. How can I achieve this sorting by group?

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>

Answer №1

Looks like this code organizes products by their respective groups and generates an HTML table for each group.

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;
    }
}

Answer №2

Utilizing the script below will sort through arr for the suitable course and will display them in the sequence specified 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>Joe's Diner - Dinner Menu</h2>
  <div class="products"></div>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for toggling between enabling and disabling the 2 instances of bvalidator

Running on my form are two instances of bvalidator found at . The first instance validates the entire form, while the second instance only partially validates the same form. In total, the form contains 2 buttons: The first button saves form data upon va ...

I'm curious about the distinction between React's one-way data binding and Angular's two-way data binding. Can someone please clarify the key differences

My understanding of these concepts is a bit hazy. If I were to develop the same ToDo application using AngularJS and ReactJS, what exactly distinguishes React ToDo's use of one-way data binding from AngularJS's two-way data binding? From what I ...

I am looking to create a PHP script that restricts access to individuals under the age of 18 based on the current

I'm looking for a way to use Php, javascript, or ajax to restrict access for individuals under 18 years old based on the current date. Any suggestions on how I can achieve this? Could someone please review my code for calculating age onblur or onSubm ...

Animating the opacity of elements using jQuery and CSS

Trying to put together a fading slideshow with five slides that will loop back to the beginning. My code seems like it should do the trick, but there's something not quite right. <script type="text/javascript"> $(document).ready(function( ...

Guide to converting a JSON object into a plain comma-separated string in PHP

let $data = [{name:'abaneel',age:23}, {name: 'john', age: 32}, {name: 'Dev' , age:22} ]; Is there a way to transform this JSON object into a simple string like the example below using PHP: $simpleString ="abaneel,23, ...

Error: The variable "details.date.getTime" is not defined and cannot be accessed

Currently, I am utilizing https://github.com/zo0r/react-native-push-notification to display notifications. Specifically, I am using scheduled notifications with datetimepicker. Previously, I have successfully used this in another project without any errors ...

Example of VPAID pre-roll ads

I've been searching for a VPAID code example to use in a sample preroll ad for quite some time now, but I haven't had any luck finding one. If anyone has a working example, could you please share it with me? Thank you! By the way, I am using vid ...

Error: The function `push` cannot be used on the variable `result` (TypeError)

Here is a snippet from my react component const mockFetch = () => Promise.resolve({ json: () => new Promise((resolve) => setTimeout(() => resolve({ student1: { studentName: 'student1' }, student2: { studen ...

EasyWaySaveArchive in ninja training - mastering the art of retrieving components

Recently started learning about dojo and JavaScript in general. I am currently working on a code snippet that requires a button to change based on the result of a php database query. The PHP script is already complete, and the code I am using so far looks ...

Having trouble grasping the inner workings of code while iterating through a JSON array in ReactJS

Currently, I am immersed in a school project that requires me to develop a simple CRUD web application. After weighing my options, I decided to utilize Spring Boot + ReactJS for this endeavor. The progress has been smooth so far, but I must admit that part ...

Using Node.js to handle reading files and dealing with undefined or null values

The get method is responsible for receiving a userid with an initial total number of points defined in the stcok.json file, along with various transactions stored in another file. Below are some sample entries from the stock JSON: [ { "user" ...

Converting JSON List to String List in a Spring MVC Controller

I am trying to pass the following List example: {"id":[1]} To this controller: public String addUsersToProject(@RequestBody List<String> usersIds, @PathVariable String projectTitle){..} However, I am encountering an issue where the list cannot be ...

Error encountered while trying to retrieve JSON data

After running the following code, I encountered an issue I received an error message stating: Uncaught TypeError: Cannot read property 'searchname' of undefined What could be causing this error and how can I fix it? var selectedVal = "calend ...

Troubleshooting Issue with Filtering Nested Object Array Based on Property

At the core of my data structure lies an array of orders, each containing an array of line items. These line items, in turn, are associated with their respective categories. I am currently attempting to filter the order array based on the category ID of th ...

MVC - The challenge of users repeatedly clicking the Submit button

In my MVC application, there are multiple pages where users submit a form by clicking a Submit button. Occasionally, users may click the button multiple times if they don't see an immediate response, causing the form to be submitted twice. To address ...

Guide on altering the cell's background hue depending on its value through javascript

I'm dealing with a table that has 3 columns: field1 is a Category field2 and field3 contain Measures (specifically integers 1, 2, 3, 4, and 5). Is there a way to use Javascript to conditionally format the background color of cells in the table hol ...

The technique of accessing parent props from a child composition component in React

I am trying to reduce every letter prop from the child component, Palata. How can I achieve this? index.js <Block letter="I" mb={16}> <Palata letter="I" start={4} end={9}/> <Wall/> <Empty/> <Palata le ...

The ng-click method on the checkbox input field in AngularJS is not being triggered

I'm trying to trigger a function in a toggle switch using ng-click, but the customerActiveDeactive function isn't being executed. <a title="Active/ Deactivate" > <input type="checkbox" class="js-switch" ng-init="status=True" ng-model ...

Guide on Retrieving the Current URL in NodeJS

Currently, I am utilizing express in conjunction with node.js. In my setup, the following code is present: app.get('/callback', async function (req, res) { Whenever a user reaches the callback section of my website, I expect to receive the req ...

Tips for transferring JavaScript values to PHP through AjaxWould you like to learn how to

Let's set the scene. I'm currently facing a challenge in passing Javascript values to different PHP functions within my ajax code so that they can be properly displayed on the page. Here is the snippet of my code: $("[data-departmen ...