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

Using PHP script to retrieve MySQL table values and dynamically update a live graph in a Javascript function

I've been researching similar issues for quite some time now, but to no avail. Currently, I'm utilizing Highcharts to update a graph every 3 seconds with the latest entry from a specific MySQL table. I am referring to the example Javascript code ...

Analyzing the HTTP status codes of various websites

This particular element is designed to fetch and display the HTTP status code for various websites using data from a file called data.json. Currently, all sites are shown as "Live" even though the second site does not exist and should ideally display statu ...

The received URL from the POST request in React is now being opened

After completing an API call, I successfully received the correct response in my console. Is there a way to redirect my React app from the local host to the URL provided (in this case, the one labeled GatewayUrl under data)? Any assistance would be greatly ...

How can a "Loading" message be displayed while external JavaScript is loading?

I have mastered the art of using JS or jQuery to showcase a "Loading" message during the loading process. Currently, I am working on a sizeable web application that relies on various JS dependencies, and I am seeking a way to exhibit a "loading" message wh ...

Unusual sequence of JQuery Ajax calls

Within my website, there is a project div that is displayed using EJS. The data for the projects in EJS are rendered using a forEach loop, resulting in multiple similar divs appearing on the page. Each project div is assigned an id for identification pur ...

using vuejs, learn how to retrieve properties within the .then function

This is the code I am working on: methods: { async pay() { this.$notify(`working`); if (!this.$v.$invalid) { try { var data = { to: this.to, subject: this.subject, }; let resp ...

Working with Angular2: Linking dropdown values with any number of items

Is there a way to dynamically bind drop down values with numbers from 1 to 100 using a loop in Angular2? I am currently using Ngprime dropdown for a limited number of values, but how can I achieve this for any number of values? Here is the template: < ...

Getting the version from package.json in Next.js can be easily achieved by accessing the `version

In my quest to retrieve the "version" from the package.json in a Next.js application, I encountered a roadblock. I attempted using process.env.npm_package_version, similar to how it is done in a Node application, but unfortunately, it returned undefined. ...

Generating a multidimensional associative array based on user inputs from a form

What is the best way to transform form input data into a multidimensional associative array? This is how the form appears: <div id="items"> <h4>Engraving Text</h4> <div class="item" data-position="1"> <h4 id="en ...

Nativescript encountered an error regarding faker: module './address' not found

Currently in the process of learning nativescript, I am experimenting with using faker to generate some data while working with typescript. Here are the versions I am using: Node - 6.9.4 Faker - 3.1.0 Typescript - 2.1.4 Encountered an error which i ...

Updating dynamic parameter in a NextJS 13 application router: A complete guide

In my route user/[userId]/forms, I have a layout.tsx that includes a Select/Dropdown menu. The dropdown menu has options with values representing different form IDs. When the user selects an item from the dropdown, I want to navigate to user/[userId]/form ...

What is the best way to position an image alongside text using Vue and Buefy?

I'm looking to add an image next to my text in Vue using Buefy. Take a look at the code I have so far, can someone offer some guidance? <template> <section class="hero is-link is-fullheight-with-navbar"> <div cla ...

Error TS 2322 - The property 'id' is not present in the object of type '{ id: number'

Just starting out with Angular and TypeScript. I created a model with the same properties but encountered an error and am struggling to find a solution: TS2322: Type '{ id: number; model: string; plate: string; deliveryDate: string; deadline: st ...

Error: The function "execute" has not been declared

Hey there! I've created a Discord bot that is meant to check the status of a Minecraft server, but I'm encountering an issue with the embed. It's showing this error: UnhandledPromiseRejectionWarning: ReferenceError: execute is not defined. ...

Sort through the array using a separate array in Vuejs

I am currently working with two arrays: { "products": [ { "name": "Jivi", "Hint": "45-60 IE/kg alle 5 Tage\n60 IE 1x/Woche\n30-40 IE 2 x/Woche", "frequency": ["1", "2", "8"] }, { "name": "Adynovi", ...

Executing Ajax requests to interact with a RESTful API

After developing a back end REST API using Slim Framework and closely following the REST format, I ran into an issue when working on the Front End. It seems that AJAX functions well with parameters but not paths. I am considering outsourcing or creating a ...

Managing numerous API requests in React Native

As I work on implementing a search field, I've encountered a challenge. Whenever a user enters text in the search field, a timer resets to 300 ms before an API call is sent to fetch autocomplete results. After receiving these results, the app then wai ...

How can jQuery help me load a lengthy webpage with various backgrounds that change according to the vertical scroll value?

I have been given a design that is 960px wide and approximately 7000px tall, divided into five segments stacked vertically at random points. There is a fixed sidebar that scrolls to each segment when a navigation link is clicked. The layout includes slider ...

I recently started learning Next.js and I'm interested in organizing my website with multiple page folders but still using a single dynamic route labeled as [id]

my-nextjs-app/ |-- .next/ |-- node_modules/ |-- public/ |-- src/ | |-- components/ | |-- men/ | | |-- [id]/ | | |-- page.tsx # Specific ID static page for Men's category | | |-- page.tsx # General stat ...

Integrating eBay API with Node.js

Hello, I am new to Node.js and I could really use some assistance with exporting console log data to an HTML page. I came across a helpful example on GitHub at this link: https://github.com/benbuckman/nodejs-ebay-api My current issue is that although I h ...