Utilize Typescript or JavaScript to dynamically access the names and values of class members

I'm relatively new to these programming languages and I know it may not be too difficult, but I am struggling to figure out how to dynamically access class instance variables.

My goal is to display an instance's variables in a table using Angular. I want to create a single function that can work with any class.

For example, let's consider a workbook class:

export class workbookEntity {
    public name: string;
    public creationDate: string;

    constructor() {
        this.name = 'my work book name';
        this.creationDate = '2018/01/26';
    }
}

Now, suppose I need to retrieve the names and values of the variables from an instance of this class within another class' function:

export class showClassComponent {
    // some code here

    whenSubmittedInHtmlForm(className: string): void {
        // logic to iterate through instance
        // className parameter will be 'workbookEntity'
    }

    // more code here
}

How would you iterate through the instance to retrieve each variable's name and value in order to achieve something like this?

[
    {
        name: 'name',
        value: 'my work book name'
    },
    {
        name: 'creationDate',
        value: '2018/01/26'
    }
]

Answer №1

There isn't much of a reflection concept in Typescript, making it challenging to perform type lookups directly. However, one workaround could be...

export class DisplayClassComponent {
    let classes = [ { name: 'workBookEntity', value: new WorkBookEntity() }]

    onSubmitHtmlForm(className: string): void {
        let foundClass = classes.filter(class => class.name == className)[0];
        if(foundClass) {
            let result = [];

            for (var key in foundClass) {
                if (foundClass.hasOwnProperty(key)) {
                    result.push({ name: key, value: foundClass[key] });
                }
            }

            return result;
        }
    }

    // additional code goes here
}

Answer №2

To maintain accurate type information, consider creating a pick utility function that can be imported into your class module whenever necessary.

let workBook = new WorkbookEntity();

export function select<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
  let newObj = {} as Pick<T, K>;
  for (const key of keys) {
    newObj[key] = obj[key];
  }
  return newObj;
}

console.log(select(workBook, ['name', 'creationDate']));

// log: { name: 'my work book name', creationDate: '2018/01/26' }

You can then import the initial function into another utility function to handle multiple objects if needed.

export function selectObjects<T extends object, K extends keyof T>
  (objects: T[], keys: K[]): Pick<T, K>[] {
  return objects.reduce((result, obj) => [...result, select(obj, keys)], []);
}

let workbooks = selectObjects([workBook, workBook2], ['name']);
workbooks[0].name // this exists
workbooks[0].age // Typescript error.

The editor will display an error for age not existing since it was not selected.

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

Decorators do not allow function calls, yet the function 'AngularSignaturePadModule' was invoked

Currently, I'm facing a problem with Angular Signature Pad. Specifically, there seems to be an issue with this particular line of code: AngularSignaturePadModule.forRoot(), ERROR in Error during template compile of 'AppModule' Function ...

Difficulty with Vue.js updating chart JS label names

I have been working with Vue JS and implementing a chart in my single page application. However, I am encountering difficulties updating the Legend and despite numerous attempts and searches, I am unable to get it to update. Any assistance in correcting my ...

Flashing background color appears as I scroll

Whenever a user touchstarts on a div, I want to apply a background-color to that specific div. Then, as the user scrolls, I use the $(window).scroll event to either reset or remove the background-color from all divs. However, my issue arises when a user b ...

Is the ID sent upon selection change?

<select class="form-control" type="text" required (change)="onChangeLov($event)">> <option value=""></option> <option *ngFor ="let contact of contacts">{{contact.id}} - {{contact.name}}, {{contact.ptechnologyName}}, ...

The JSON found in the request body is not valid according to Node JS

I encountered an error stating that the request body contains invalid JSON, despite my JSON being valid. I used JSON.parse to convert my string to JSON. Below is the code snippet for the body: var formdata = JSON.parse('{"content":"thi ...

Parsing a JSON array using Moment.js within a subscription function

I have a series of time entries within a data JSON array that I need to parse and format using Moment.js. The formatted data will then be stored in the this.appointmentTimes array for easy access on my view using {{appointmentTime.time}}. Here is the JSON ...

CKEditor's height automatically increases as the user types

I am using a ckEditor and looking for a way to make its height automatically grow as I type. https://i.stack.imgur.com/m7eyi.png <textarea name="description" id="description"> </textarea> <script> CKEDITOR.replace( 'description ...

Tips for avoiding API calls at specific intervals while in the process of logging out from a web application

I have integrated a 60 second timer observable in my Ionic/Angular app, which emits the current time synchronized with the server time. Every minute, I fetch permissions, settings, and other data by passing a token with each request. Upon logout, I revoke ...

Struggling to target the child elements of an unordered list with jQuery?

Need help with selecting the children of a list item in a jQuery mobile navigation? I am having some trouble with this task. Here is a fiddle demonstrating what I have done so far: http://jsfiddle.net/jhrz9/ <div data-role="panel" id="left-panel" data ...

Triggering events on multiple elements with Vue.js when clicked

I am currently working on a feature that involves hiding and showing descriptions of image thumbnails when clicked by the user. I tried following a VueJS tutorial on transitions, but unfortunately only one thumbnail is properly functioning while the rest a ...

Navigating through child components in React

As a newcomer to react application development, I recently embarked on my first project. My goal was to showcase 5 buttons within a table. Initially, I took the straightforward approach of hardcoding them in Table.js Table.js <Button hidden={ ...

How to Retrieve the Order Number of an Object in an Array using JavaScript ES6

Curious about JavaScript ES6 and needing assistance! I have a simple question - how can I determine the order number of an object in an array? [ { "pk": 23, "image": "http://localhost:8000/media/users/1/2_27.jpg"}, { "pk": 11, "image": "http://localho ...

Why does the array format of the values saved in app.locals seem to disappear when they are accessed in the view?

I have created a date values array and stored it in an app.locals variable using the code snippet below: prepDataList.forEach(function(item){ var str = item.createdAtDate.toDateString(); //str = str.substring(4, 10); labelsArray.push(str); counts ...

Trouble with fill() function

Check out this JavaScript code snippet I wrote: function Show(output, startX, startY){ var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); context.arc(startX, startY, 3, 0, Math.PI*2, true); context.fill( ...

Trying to utilize transformResponse in queryFn within Redux Toolkit Query but failing to retrieve the desired value

When attempting to alter the backend response using the transformResponse function, I encountered an error even when simply returning the "baseQueryReturnValue" argument. export const categoryApiSlice = createApi({ reducerPath: "Categories", baseQ ...

Why isn't jQuery working properly for showing/hiding elements?

I am attempting to create a functionality where the string remove field can be toggled to show or hide using a single button, depending on its current state. Initially, it should be hidden (using the hidden HTML attribute), and upon clicking the button, it ...

I encountered a TypeError when attempting to load MDX in Next.js with the mdx-js/react library

My Goals and Assumptions for the Project Please note that this question has been translated using Deepl Translations. I aim to integrate mdx-js/react into Next.js for loading mdx files. Environment Details: Operating System: macOS Big Sur Node Version: ...

Guide on incorporating vanilla JavaScript into a personalized Vue component

I'm currently working on incorporating a basic date-picker into a custom Vue component. Since I am not utilizing webpack, I want to avoid using pre-made .vue components and instead focus on understanding how to incorporate simple JavaScript into Vue. ...

Guide on utilizing "setFont" in jsPDF with UTF-8 encoding?

Currently working on a project using Angular 7 I am trying to incorporate a custom font (UTF-8) into my PDF generation service using jsPDF. Despite researching various examples, none seem to work for me. The documentation on the jsPDF GitHub page mentions ...

The Best Way to Filter Mongo Documents Using Nested Objects

Is there a way to locate a room by its ID and confirm that it includes the current player? Within my mongodb database, I have a collection of rooms that contain players who are users. const RoomSchema = new Schema({ players: [{ type: Schema.Types.Objec ...