Generating HTML content using JavaScript object data

I have a JavaScript file that holds data in the form of objects :

let restaurant_A = {
    name: "BBQ place",
    min_order: 20,
    delivery_charge: 5,
    menu: {
        //First category
        "Appetizers": {
            //First item of this category
            0: {
                name: "Appetizer1",
                description: "It's an appetizer",
                price: 4.00
            },
            1: {
                name: "Appetizer2",
                description: "It's another appetizer",
                price: 7.50
            }
        },
        "Combos": {
            2: {
                name: "Combo 1",
                description: "It's a combo",
                price: 13.33
            },
            3: { 
                name: "Combo 2",
                description: "another combo",
                price: 13.33
                
            }
        },
        "Drinks": {
            4: {
                name: "Juice 1",
                description: "It's a juice",
                price: 5.99
            },
            5: {
                name: "Juice 2",
                description: "It's a juice",
                price: 5.99
            }
        }   
    }
};

I would like to dynamically recreate the structure below:

<div class="menu__items">
    <div id="appetizers">
        <h2>Appetizers</h2>
        <div id="appetizer1">
            <h3>Appetizer1</h3>
            <p>It's an appetizer</p>
            <p>$4.00</p>
        </div>
        <div id="appetizer1">
            <h3>Appetizer2</h3>
            <p>It's another appetizer</p>
            <p>$7.50</p>
        </div>
    </div>
    <div id="combos">
        <h2>Combos</h2>
        <div id="combo1">
            <h3>combo1</h3>
            <p>It's a combo</p>
            <p>$13.33</p>
        </div>
        <div id="combo2">
            <h3>combo2</h3>
            <p>another combo</p>
            <p>$13.33</p>
        </div>
    </div>
</div>

I am looking to achieve this using only JavaScript. I have attempted to append and create new elements, but I find myself having to repeat the process for each object. I believe creating a function that iterates through all the objects and generates new elements is the way to go, but I am unsure. How should I approach this?

Answer №1

let restaurant_A = {
    name: "BBQ place",
    min_order: 20,
    delivery_charge: 5,
    menu: {
        //First category
        Appetizers: {
            //First item of this category
            0: {
                name: "Appetizer1",
                description: "It's an appetizer",
                price: 4.0,
            },
            1: {
                name: "Appetizer2",
                description: "It's another appetizer",
                price: 7.5,
            },
        },
        Combos: {
            2: {
                name: "Combo 1",
                description: "It's a combo",
                price: 13.33,
            },
            3: {
                name: "Combo 2",
                description: "another combo",
                price: 13.33,
            },
        },
        Drinks: {
            4: {
                name: "Juice 1",
                description: "It's a juice",
                price: 5.99,
            },
            5: {
                name: "Juice 2",
                description: "It's a juice",
                price: 5.99,
            },
        },
    },
};

const itemsElement = document.querySelector(".menu__items");

for (const [category, items] of Object.entries(restaurant_A.menu)) {
    const categoryElement = document.createElement("div");
    categoryElement.id = category.toLowerCase();

    const headingElement = document.createElement("h2");
    headingElement.textContent = category;
    categoryElement.appendChild(headingElement);

    for (const [index, item] of Object.entries(Object.values(items))) {
        const itemElement = document.createElement("div");
        itemElement.id = `${categoryElement.id.replace(/s$/, "")}${parseInt(index) + 1}`;

        const headingElement = document.createElement("h3");
        headingElement.textContent = item.name;
        itemElement.appendChild(headingElement);

        const descriptionElement = document.createElement("p");
        descriptionElement.textContent = item.description;
        itemElement.appendChild(descriptionElement);

        const priceElement = document.createElement("p");
        priceElement.textContent = `$${item.price.toFixed(2)}`;
        itemElement.appendChild(priceElement);

        categoryElement.appendChild(itemElement);
    }

    itemsElement.appendChild(categoryElement);
}
<div class="menu__items"></div>

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

How to manage multiple controllers for the same template in AngularJS?

I am facing a requirement where a single page needs to display a lot of different data, all within one vertical-scrolling page. To manage this, I have implemented collapsible divs on the page controlled by ng-if to efficiently handle the DOM elements. In ...

Increasing Taxes and Boosting the Overall Cost

How can we set up a system where taxes are bypassed by default unless otherwise specified when placing an order? Let's take a look at the following text box: <input class="txt1" type="text" name="subtotal" value="" id="subtotal" size="16" ta ...

Issue with running gulp ser on first attempt in SPFX

Every time I try running gulp serve, I encounter the following issue: Error: Unable to locate module '@rushstack/module-minifier-plugin' Please assist me with this problem. Thank you! ...

Firefox Cookie Expiry Date Automatically Set to One Week in Default Settings

I recently encountered an issue while trying to create a cookie that would persist for a year. Interestingly, the code I used worked perfectly on Chrome, as I could verify by checking the "Storage" in the dev tools. However, when I tried the same code on F ...

Adjust the font size to fit within the container

My webpage features a bootstrap 4 container with three columns that adjust on screen sizes above the md breakpoint (col-md-4). Each column contains an img with the class img-fluid, and when hovered over, text description appears. I want this hover text to ...

Deciding the source URLs for external iframes

Is it possible to detect the URL displayed in an iframe? How can we ensure that links within an iframe open in a new tab/window? Moreover, is there a way to achieve this even with the same-origin policy for external frames? If not, what causes this violat ...

Altering the color of a Fabulous Icon in real-time

I'm having trouble changing the color of an Awesome Icon with this code I created. Instead of getting the desired color, I am getting 'undefined' as a result. <script type="text/javascript"> function changeAIColor(idName) { alert ...

Error: The variable $ has not been declared in the context of the function iterateId

I understand that there are many questions on SO related to this error, but my issue is a bit unique. In my code, I am using a forEach loop to retrieve the IDs and text of elements as shown below: function iterateId(id){ $("input[id*='" + id + ...

An unexpected error causes the entire application to come to a halt, specifically due to a property being undefined. Assistance is

Issue Reproduction: 1. We have a list of advertisers (our clients) for whom we run various marketing campaigns. 2. Upon clicking the "Campaign" button for a specific advertiser. Result: You are taken to the "campaigns" page displaying all campaigns for ...

Parsing form bodies in Express.js allows for easy extraction of data

Below is an example of a form: <!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> < ...

Effortless code formatting with VS Code for TypeScript and JavaScript

Does anyone know of any extensions or JSON settings that can help me format my code like this: if(true) { } else { } Instead of like this: if(true){ } else { } ...

Error: Unable to retrieve the specified ID

One unique aspect of my backbonejs app is the model structure: var Store = Backbone.Model.extend({ urlRoot: "/stores/" + this.id }); This is complemented by a router setup like so: var StoreRouter = Backbone.Router.extend({ routes: { 's ...

Get all the classes from the body element of the AJAX-loaded page and update the body classes on the current page with them

I am currently in the process of AJAX-ing a WordPress theme with a persistent music player. In Wordpress, dynamic classes are used on the <body> tag. The structure I'm working with looks like this: <html> <head> </head> ...

Having difficulty with a button in a Navbar using Python and Selenium

As a newcomer to Selenium, I am currently attempting to automate the login process for a specific site but have hit a roadblock with clicking on the drop-down button in the navigation bar. Below is my current code: from selenium import webdriver from sel ...

What is the process for removing a document attribute in Sanity iO?

I have a collection of objects within my Sanity Document named Images which includes Comments An example comment object in the comments array looks like: { "_key": "6510dc79cf8b", "comment": "Hello world" ...

Generating various arrays of data

I am currently facing an issue with creating separate datasets based on the month value. Despite my efforts, all month values are being combined into a single dataset in my code. Any assistance in dynamically generating different datasets would be greatly ...

Using Vue to make a REST API call in a JavaScript file

I have been trying to convert an Axios API call from a Vue page into a standalone module that can be reused multiple times in my app. Unfortunately, all my attempts so far have failed and I'm not sure if it's because I lack experience working wit ...

Remove the scrollbar from the iframe and instead display a scrollbar on the page in its place

Currently, I am facing an issue with the vertical scrollbar on an iframe. I want to remove it so that the scrollbar appears on the main page instead. This way, I will be able to scroll the content of the iframe using the page's scrollbar. I managed to ...

Tips for Saving JSON Response from Fetch API into a JavaScript Object

I am facing an issue trying to store a Fetch API JSON as a JavaScript object in order to use it elsewhere. The console.log test is successful, however I am unable to access the data. The Following Works: It displays console entries with three to-do items: ...

Challenges with Page Loading in Selenium

Inquiry: When a URL is accessed in a web browser, the page begins to load. A loading symbol appears at the top, and once it stops, our selenium script continues with the next steps. However, there are instances where the page takes longer to load all its ...