Displaying a collection of objects in HTML by iterating through an array

As someone new to coding, I am eager to tackle the following challenge:

I have designed 3 distinct classes. The primary class is the Place class, followed by a restaurant class and an events class. Both the restaurant class and events class inherit core properties from the Place class while also possessing additional properties unique to each of them. Each class includes a display() function that showcases their individual content. To populate my page, I have created two objects per class which are stored in an array to be iterated through for display.

The class with the display function is outlined below:

class Place {
Name = "";
City = "";
ZIP = "";
Address = "";
Image = "";

constructor(Name, City, ZIP, Address, Image){
    this.Name = Name;
    this.City = City;
    this.ZIP = ZIP;
    this.Address = Address;
    this.Image = Image;
}

display(){
    $("cardContainer").append(`
        <div class="col-lg-3 col-md-6 col-sm-12">
                <div class="card" style="width: 18rem;">
                    <img src="${this.Image}" class="card-img-top" alt="...">
                    <div class="card-body">
                        <h5 class="card-title">${this.Name}</h5>
                        <p class="card-text">${this.City},<br>${this.ZIP} ${this.Address}</p>
                    </div>
                </div>
            </div>  
        `);
}

In a similar manner, I implemented the restaurant and events classes. Subsequently, I initialized an array and added the objects:

let placesArr = [];

placesArr.push(
    new Place(
        "La Sagrada Familia",
        "Barcelona",
        "08013",
        "Carrer de Mallorca 401.",
        "img/sagradafamilia.jpg"
        )
);
new restaurant(
    "Raco del Nuria",
    "Barcelona",
    "08002",
    "La Rambla 133.",
    "img/racodelnuria.jpg",
    "+34-933-01-05-77",
    "Mediterranean",
    "racodelnuria.com"
);
new events(
    "FC Barcelona vs. Athletic Club de Bilbao",
    "Barcelona",
    "08028",
    "C. d'Aristides Maillol 12.",
    "img/foci.jpg",
    "06.23.2020",
    "22:00",
    "from 29 euro"
);

After testing the code using console.table, it was confirmed that everything worked as intended and all data displayed correctly in the console.

Now, the final step involves looping through the array and presenting the content in the HTML. The webpage only consists of an empty div with the class="row" and id="cardContainer", but I am unsure how to proceed. Could anyone provide guidance on this matter?

Answer №1

Utilize the existing display function for appending template literal HTML by implementing this code snippet:

placesArr.forEach(place => place.display())

Answer №2

Here is an example that you can utilize:

var table = '<md-table-container>' + '<table class="md-table" border="1" style="text-align:center">' + '<thead class="md-head">' + '<tr md-row>';
for (i = 0;i < data.length; i++) { //you have the option to use your own array here
table += '<th class="md-column">' + data[i] + '</th>';
}
table += '</tr></thead>';
table += '</table></md-table-container>';

You can then add it using $("cardContainer").append(table)

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

Tips for providing certificate key file during the deployment of a cloud function?

Within my TypeScript file, the following code is present: import * as admin from 'firebase-admin' import * as functions from 'firebase-functions' const serviceAccountKey = "serviceAccountKey.json" const databaseURL = "https://blahblah. ...

Is it possible to utilize router.push within Redux thunk? Is this considered a beneficial approach?

I have this anchor element: <a className="btn btn-sm btn-circle" href={`https://www.facebook.com/sharer/sharer.php?u=${ process.env.NEXT_PUBLIC_ENVIRONMENT == "prod" ? "https://tikex.com" : "https:/ ...

Can't access innerText in Firefox

This is the code snippet I'm having trouble with: <div id="code">My program<br />It is here!</div> <script type="text/javascript"> var program=document.getElementById('code'); ShowLMCButton(program.innerText); </s ...

Material UI - Exploring the Tree View Component

Seeking advice on structuring server data for utilization with the TreeView component from Material UI: https://material-ui.com/api/tree-view/ I need to efficiently handle large datasets by fetching child nodes dynamically from the server upon user intera ...

Angular 11 is indicating that the type 'File | null' cannot be assigned to the type 'File'

Hey there, I'm currently diving into Angular and I'm working on an Angular 11 project. My task involves uploading a CSV file, extracting the records on the client side, and saving them in a database through ASP.NET Web API. I followed a tutorial ...

Troubleshooting: Issue with NodeJS Mongoose async function not returning value

Having an ongoing issue with retrieving a value from my async functions in the mongoose service. The problem persists as it consistently returns undefined, leaving me puzzled about what's going wrong. Being new to this area, any assistance would be gr ...

Warning: multiple selections have been made on the checkboxes

Currently, I am using FormData to submit data and trying to alert the values of checked checkboxes in my form. At the moment, I can only make it work for one checkbox. How can I alert the values of all checked checkboxes? var formData = new FormData(docu ...

Update submenu panel in jQuery Mobile version 1.4.3 following AJAX request

Hello there, I am currently in the process of developing my first JQuery Mobile website. One of the key features I have implemented is a panel for navigation. Each individual page includes the panel, along with an icon in the header that serves as the butt ...

Having trouble getting the Vue.js framework to function properly on a basic HTML page with a CDN implementation

I recently delved into learning vue.js and decided to focus on forms. However, when I tried to open the file using a live server or XAMPP, it didn't work as expected. It had worked fine before, but now I seem to be encountering some issues. Could anyo ...

Sort a JSON object in ascending order with JavaScript

I have a JSON object that needs to be sorted in ascending order. [{ d: "delete the text" }, { c: "copy the text" }] The keys d and c are dynamically generated and may change. How can I sort this into? [{ c: "copy the text" }, { d: "delete the text" }] ...

How to accentuate search results using Angular filters and conceal non-matching text?

Recently, I came across an interesting example of using Angular filter to highlight search results. It works well in highlighting the word 'suit', but I noticed that all non-matching text remains visible. If you'd like to see the example I ...

What could be causing the mousewheel event in my code to remain active?

Whenever I try to scroll on Google Chrome, an error occurs on my website. jquery-3.3.1.min.js:2 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See To resolve this issue: $(document).ready(f ...

Is it possible to simultaneously run two Node.js projects on Windows?

Is it possible to run two Node.js projects on a Windows operating system? If so, what is the process for doing that? If not, can I run two Node.js projects on a dedicated host instead? ...

Is Next.js experiencing issues with animating presence specifically for exit animations?

I'm facing an issue with adding an exit animation to my components in next js. Despite setting an initial animation, the exit animation doesn't seem to work as expected. Could someone please help me figure out what I'm doing wrong here? Be ...

Secrets to concealing a Material UI column based on specific conditions?

Recently, I encountered a challenge with my MUI datagrid where I needed to hide a column based on a specific role. Below is the code snippet: const hideColumn = () => { const globalAdmin = auth.verifyRole(Roles.Admin); if(!globalAdmin){ ...

How to extract data from JSON files using Angular 12

Having trouble with Angular and TypeScript. Need to fetch a GET API from Spring where the return variable is Page, but the JSON structure looks like this: "content": [ { "id": 1, "category": "TSHIRT&qu ...

Adjusting the image placement within a modal window (using bootstrap 3)

Behold, an example modal: <!-- Large Modal --> <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"> <div class="modal-dialog modal-lg"> <div class="modal-content"> ...

How to style a date and time object using angularjs

What is the best way to convert a PHP datetime object to the format "May-27-1990"? ...

JavaScript format nested data structure

For my latest project, I am working on a blog using Strapi combined with Nuxt. To fetch the categories and articles data for my blog, I send a JSON object from my front-end application using Axios. { "data": [ { "id": 1, ...

Combining a group of primitive data types in Java using a separator

Let's say I have an array: int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7}; I want to combine the elements of this array using a separator, such as " - ", resulting in a string like this: "1 - 2 - 3 - 4 - 5 - 6 - 7" Is there a way to achieve this? PS ...