"JavaScript allows for object string keys to be listed as enumerable properties

Within my setup, I have a class that contains string keys as follows:

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

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

The main objective is to iterate dynamically through the functions within an instance like so:

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

Despite various attempts, all efforts have only revealed the keys `id` and `data`.

I am able to manually retrieve and execute the function successfully:

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

However, it does not appear in any dynamic listing method I have experimented with.

Setting the enumeration manually also proves effective:

class MyClass {
    constructor() {
        this.id = 0
        this.data = []
        
        // Attention!!!
        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"]

Yet, this approach contradicts the fundamental purpose of achieving dynamism. Is there a way to dynamically fetch function names associated with string keys or make every property enumerable?

Answer №1

list(MyClass.__dict__.keys())

yields

["__init__", "GET /info"]

Answer №2

To accomplish this task, you have a couple of options:

Object.getOwnPropertyNames(myObj)

Alternatively,

for (const prop in myObj) {
}

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

Error message: "jQuery TypeError - function was not found"

When attempting to retrieve properties of a div using the code below (function ($) { function StickyNotes() { this.getProperties = function (note) { var properties = {}; properties['top'] = note.position().top; prope ...

Conceal an item if the span element encompasses a div with a specific class

I am struggling with a problem where I need to hide an "i" element only if a "span" contains a "div" element. The content inside the "span" is loaded via AJAX and rendered as HTML, so it may contain the "div class=difference" or not. The code snippet in q ...

Order and filter Mongoose documents based on populated fields

I am working with collections for users, news, and user-news. In the "user-news" collection, I have data populated from both the "user" and "news" collections. My question is: Is it possible to sort and search documents in the "user-news" collection by fi ...

Updating class on elements in arrays

There are multiple elements, each with a unique ID "xxx_view_ch_&&&" within an outer div with the ID "xxx_view_&&&". The goal is to change the class of the element with the ID "xxx_view_ch_&&&" when the user clicks on the entire element ("xxx_view_&&&"). ...

Unexpected error in log4javascript on IE8: Expected function not found

I'm attempting to redirect console calls to the log4javascript library. Essentially, any usage of console.log should trigger log.info, with log being an instance of Log4javascript. However, when log.info is invoked, I encounter a "Fonction attendue" ...

Encountered an issue while compiling code using the Istanbul plugin

I'm currently working on generating a code coverage report for my ReactJS project using the babel-istanbul-plugin. However, when I incorporate "istanbul" as a plugin in my .babelrc file and attempt to build, I encounter the following error: ERROR in ...

Module.exports causing keyword errors in eslint

Encountering some unusual errors from eslint CI regarding my jest.config.js file. 1:1 error Rule 'no-empty-label' has been replaced by: no-labels no-empty-label 1:1 error Rule 'no-reserved-keys' has been replaced ...

What is the proper way to create a regex pattern that specifies 'without any spaces'?

I need assistance in creating a regex expression that specifies "and NO whitespaces". I have to incorporate this into the following if statement shown below: $('#postcode').blur(function(){ var postcode = $(this), val = postcode.val(); ...

What steps can I take to resolve the issue in my code? I keep receiving a type error stating that it cannot read

I seem to be encountering an issue when running my code where I receive a 'cannot read property 'age' of null'. This error breaks my code, and I'm trying to figure out how to implement a check to ensure it only runs when I am signe ...

Exploring TestCafe and Testing Library: How to destructure multiple selectors with one selector

Currently facing a challenge with writing a test using testcafe and testing library. Given the site's unique characteristics, we are unable to utilize the standard testing library role with name/label queries as our tests run across 50+ different loc ...

generate an array composed of promises to be used with Promise.all

Currently, I am working with an array of file paths and my goal is to read all the files inside a Promise.all function, followed by carrying out several tasks. var files = ["./file1.txt", "./file2.txt"] Promise.all(files.forEach(file=>{ /* read file ...

Dropzone is encountering an issue with uploading photos: The upload path seems to be invalid

Despite thoroughly checking the path settings in my code, the error message persists when I attempt to upload photos using Dropzone. It seems to be indicating a problem with the upload path. What could be causing this issue? I am currently in the process ...

Pass data from a JavaScript function to Objective-C in Xcode by returning an array

How can I retrieve an array of strings from Javascript in my iPhone app code? I am calling a Javascript function, and once it completes, I need to send the array of strings back to the Objective-C code. What is the best way to return the array and how can ...

Error in React Router: 'Home' is undefined

UPDATE: A huge shoutout to all you awesome individuals! The key here is using import/export syntax to ensure everything runs smoothly. I'm encountering an issue where I keep seeing Uncaught ReferenceError: Home is not defined while trying to implemen ...

Differences in Angular 2 Performance: Analyzing AOT and JIT Payloads

I'm still getting the hang of Angular 2, so feel free to correct me if I'm off base. Comparing Angular 1 and 2 in terms of the compiler: In Angular 1, the compiler is more general and dynamic, meaning that a single code is used for dirty checki ...

Discovering how to locate a div element in one component from a separate component using Vue.js

Imagine having multiple Vue.js components in one project. <loginFields></loginFields> <submitButton></submitButton> Now, when the submitButton (which is a div with a unique id) is clicked, I want to initiate a method that checks t ...

How can I expand my Jquery slideshow to occupy the entire screen?

I am working on stretching my JQuery slideshow to fit the entire browser, but I am running into some difficulty. I have downloaded the jQuery Vegas plugin, but I can't seem to figure out what the problem is. I would like my slideshow to resemble the o ...

Transforming the JSON data into a text format

I have a JSON object structured like this: { "name": "ok", "country": "US", "phone": "900", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f70745f727e767331707c">[email protected]</a>", ...

Employing the powerful Math.pow() function within the setState() method

In this ReactJS code example, the goal is to update the value of a div element with every click of a button using the Math.pow() method. However, it seems that the method is not working as intended. Can someone explain why? The handlerButton function in ...

How to Send and Receive GET Requests including Parameters

When faced with the task of retrieving all records from a database based on a specific id, the process involves initiating a request from JavaScript. This request is then captured by a Servlet which accesses a DAO to query the database. Subsequently, the r ...