What is the best approach for showcasing the contents of an array with class attributes in TypeScript?

Here is an example code snippet for adding a single item from a pre-written array to a table. In this case, we have a simple name element so only one "< td>${people[i]}< /td>" tag is needed to display the names.


let people: string [] = ["Jack", "Michael"]

for (let i: number = 0; i < people.length; i++) {
document.getElementById ("buddies").innerHTML +=
`<tr>
<td>${people[i]}
<tr>`;
}

If you want to achieve the same result using a class instead of directly writing content into the array, you can follow this approach:


class Person{
public FirstName : string
public LastName : string
constructor (Firstname: string, Lastname: string) {
this.FirstName = Firstname;
this.LastName = Lastname;}

let people: Person [] = [
new Person ("Peter", "Parker")]

for (let i: number = 0; i < people.length; i++) {
document.getElementById ("table").innerHTML +=
`<tr>
<td>${people[i].FirstName}             //this is where the first name should be//
<td>${people[i].LastName}             //this is where the last name should be //
<tr>`;
}

If you are encountering issues such as displaying [object Object] in your table row, try assigning the specific properties of each object (in this case, FirstName and LastName) to ensure correct rendering in the table.

Hope this helps steer you in the right direction!

Answer №1

Alright, in this scenario individuals represents an array containing instances of the class Person, each object belonging to the Person class with properties like FirstName and LastName.

As you loop through the individuals array, you can access its attributes using individuals[i].FirstName and individuals[i].LastName.

 for (let i: number = 0; i < individuals.length; i++) {
    document.getElementById ("table").innerHTML +=
    `<tr>
    <td>${individuals[i].FirstName}
    <td>${individuals[i].LastName}
    <tr>`;
 }

The revised code snippet should resemble the following:

<table id="table"></table>

<script>
  // Crafted using JS syntax, albeit TypeScript follows a similar structure
  class Person{
      constructor (Firstname, Lastname) {
         this.FirstName = Firstname;
         this.LastName = Lastname;
         }
   }

  let individuals = [new Person ("Alice", "Smith"), new Person ("Bob", "Johnson")]

  for (let i = 0; i < individuals.length; i++) {
    document.getElementById("table").innerHTML +=
    `<tr>
    <td>${individuals[i].FirstName}
    <td>${individuals[i].LastName}
    <tr>`;
  }

</script>

Moreover, the original code has a few errors such as missing closing brackets for the class definition. Remember, defining a class is done as shown below

class Person{
 ...
}

and not as

class = Person{
  ...
}

For more examples and information, refer to the official documentation.

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

Efficiently managing data in arrays and lists on Android without losing existing values

Is there a way to save data into a text file without it being overwritten? Currently, I am using sharedpreferences which overwrites the data, but I would like to keep a record of the values before they are overwritten in a list or column format. For exam ...

Issue: Execution terminated with error code 1: ts-node --compiler-params {"module":"CommonJS"} prisma/seed.ts

Whenever I run npx prisma db seed, I encounter the following error: Error message: 'MODULE_NOT_FOUND', requireStack: [ '/run/media/.../myapp/prisma/imaginaryUncacheableRequireResolveScript' ] } An error occurred during the execution ...

Combining the values of two input fields in Angular

Within my form, I have three input fields labeled Name, hours, and minutes. When I execute a POST operation, I combine the values of hours and minutes into a variable named duration before sending it to the api. The resulting JSON structure appears as fo ...

React Form Hook: restoring uniform width to selectors once more

Looking to create a form using React form hooks and Material UI? Check out this link to codesandbox to see the code in action. In the CreateEmployee.tsx file under components\execute folder, you'll find the necessary code. There's also a UI ...

When using tsdx with React, null values can prevent proper usage of hooks

Recently, I attempted to develop a React TypeScript component using tsdx for compilation and encountered a roadblock while debugging. The package appears to be successfully published and installed without any errors. However, when trying to use it, I consi ...

Struggling with the error message "Uncaught ReferenceError: x is not defined"? Learn how to access data from a TypeScript bundled JavaScript file in a separate script

I am currently setting up a testing environment for TypeScript. My primary objective is to package all .ts modules into a single .js file that can be easily referenced on the client-side in a straightforward index.html. Below is an example of my test modul ...

Utilizing PHP and HTML to pull various values from a single select option

Is there a way to retrieve multiple values from a single select option value? Here is an example: <html> <form method="post" action="#"> <select name="retrive_destination"> <?php while($row = mysql_fetch_assoc($result)){ ...

how to eliminate duplicate elements from a multi-dimensional array using Python

I am working with a 2-d array xx=[[a,1],[b,2],[c,3]] Currently, I am attempting to eliminate duplicate entries from it. While a simple code like xx=list(set(xx)) works for a simple 1-D array, it results in an error when applied to 2-d elements temp = ...

Eliminate repeating elements in an array of objects with multiple levels

I'm facing a challenge with filtering an array of objects based on the condition that myDatas.items.flaggedItem should not be null, while also eliminating duplicates where myDatas.items.id are identical. This scenario should result in only 2 items bei ...

Is it possible for PHP to accomplish this task?

Is it possible for PHP to achieve this? I have a set of arrays structured like this: $x[1][2][3] = 10; $x[1][2][4] = 5; $x[1][2][3] = 2; Upon using print_r($x), the output is: Array ( [1] => Array ( [2] => Array ...

Tips for assigning a preset value to a checkbox

Is there a simple way to set the default Checked value of this angular checkbox? <p class="card-text">Please let me know which public organizations have been notified.</p> <div for="stakeholders" class="custom-control custom-c ...

Identify a duplicate class name element using Selenium

<ul class="k9GMp "> <li class="Y8-fY "><span class="-nal3 "><span class="g47SY ">2</span> posts</span> </li> <li class="Y8-fY "><a class="-nal3 " href="/username/followers/" tabindex="0"><span ...

Clear out chosen elements from Angular Material's mat-selection-list

Looking for a way to delete selected items from an Angular Material list, I attempted to subtract the array of selected items from the initial array (uncertain if this is the correct approach). The challenge I face is figuring out how to pass the array of ...

Julia's Versatile Numeric Arrays

As I dive into learning Julia through its documentation, I stumbled upon code snippets like this: function testFunction(x::Number) return x+5 end This function is designed to work with a wide range of numeric types in Julia. However, my attempt at s ...

The predicament with arranging arrays

I'm working with an array that looks like this: [ { "TaskID": 303, "TaskName": "Test1", "TaskType": "Internal", "Status": "Processing", "IsApproved": false, "RowNumber": 1 }, { "TaskID": 304, ...

The 'doRequest' property is not found on the type 'any[]'

Attempting to develop a custom hook in TypeScript for managing errors & API requests, but encountering a type error where a property does not exist on type 'any[]' Here is the code for the hook: import axios from 'axios'; import { ...

Types of Axios responses vary depending on their status codes

I am looking to create a specific type for axios responses based on the status code: types: type SuccessfulResponseData = { users: .... }; interface SuccessfulResponse extends AxiosResponse<SuccessfulResponseData, any> { status: 200; } ty ...

PHP 2D associative array losing modified values

I have encountered a perplexing issue related to PHP and a 2-dimensional associative array. I am currently taking a PHP class, but unfortunately, the instructor seems to lack expertise in this area. Initially, I declared the array as global and stored som ...

What impact does the sequence of array initialization have in an embedded system?

In my coding assignment, I am tasked with manipulating user input that includes a hexadecimal memory address and a word or phrase up to 16 characters long. Each character in the input string following the memory address is converted to a hexadecimal value, ...

Why is my RxJS timer not waiting for the specified time?

I'm diving into the world of RxJS and trying to grasp its concepts. During some testing, I encountered a puzzling issue that has me stumped. Below is the snippet in question : let item = { id: 1, name: 'chair' }; const asyncItem = timer(20 ...