Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

78
Views
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.

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

There are two ways to do this

Object.keys(myObj)

or

for (let key in myObj) {
}
over 4 years ago · Santiago Trujillo Report

0

Object.getOwnPropertyNames(MyClass.prototype)

gives you

["constructor", "GET /data"]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!