Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript make object string keys enumerable

I have a class set up with string keys, like this:

class MyClass {
    constructor() {
        this.id = 0
        this.data = []
    }

    "GET /data"(req, res) {
        res.json(this.data)
    }
}

The goal is to dynamically loop over the functions in an instance like this:

for (let key in new MyClass()) {
    console.log(key)
}

However, everything I have tried has only resulted in the keys id and data.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I can manually get the function and run it just fine:

let item = new MyClass()
item["GET /data"]()

But it does not show up in any dynamic enumeration I have tried.

Manually setting the enumeration also works:

class MyClass {
    constructor() {
        this.id = 0
        this.data = []
        
        // Here!!!
        Object.defineProperty(this, "GET /data", {
            value: this["GET /data"],
            writable: false,
            enumerable: true,
            configurable: true
        })
    }

    "GET /data"(req, res) {
        res.json(this.data)
    }
}

console.log(Object.keys(new MyClass())) // ["id", "data", "GET /data"]

But that defeats the purpose of doing it dynamically. Is there any way to either dynamically get the names of functions with string keys, or make every property enumerable?

>Solution :

Object.getOwnPropertyNames(MyClass.prototype)

gives you

["constructor", "GET /data"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading