Search code examples
javascriptangularclasstypescriptmember

Dynamically get class members names and values using Typescript or javascript


I'm pretty new with these languages and I'm sure it's not so complicated but could not find how to walk through class instance variables dynamically.

I'm trying to display instance's variables in a table using Angular. I'd like to write a single function that will work with any class.

Let's say I have a workbook class:

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

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

And let's say I want to get the names and values of the variables of an instance of this class in another class' function:

export class showClassComponent {
    // some code here

    whenSubmitedInHtmlForm(className: string): void {
        // do something to walk through instance
        // with className parameter = 'workbookEntity'
    }

    // more code there
}

How would you walk through the instance to get each variable's name and value to get something like this?

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

Solution

  • There's no concept of reflection, so much in Typescript, so you can't neccessarily do a type lookup. But you might be able to do something along the lines of...

    export class showClassComponent {
        var classes = [ { name: 'workBookEntity', value: new WorkBookEntity() }]
    
        whenSubmitedInHtmlForm(className: string): void {
            let c = classes.filter(class => class.name == className)[0];
            if(c) {
                let ret = [];
    
                for (var key in c) {
                    if (c.hasOwnProperty(key)) {
                        ret.push({ name: key, value: c[key] });
                    }
                }
    
                return ret;
            }
        }
    
        // more code there
    }