Ask Your Question
3

How can I dynamically generate JS classes as I iterate through an object?

asked 2022-12-04 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-02-09 16:00:00 +0000

lakamha gravatar image

To dynamically generate JS classes as you iterate through an object, you can use the class keyword in a loop and the eval function to evaluate the code string.

Here's an example:

// The object to iterate through
const object = {
  name: 'John',
  age: 30,
  gender: 'male'
};

// Iterate through the object and generate classes
for (let key in object) {
  // Create the class string template
  const classString = `
    class ${key}Class {
      constructor() {
        this.${key} = ${object[key]};
      }
    }
  `;

  // Evaluate the class string
  eval(classString);

  // Create an instance of the class
  const obj = new eval(`${key}Class`)();

  // Test the instance
  console.log(obj[key]); // Output: John, 30, male
}

In this example, we iterate through the object and generate classes dynamically using the class keyword and the eval function. For each key in the object, we create a class string template that defines a constructor that sets the property value based on the object value.

We then evaluate the class string using the eval function, which creates a new class in memory. Finally, we create an instance of the class and test that it has the correct property value.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-12-04 11:00:00 +0000

Seen: 12 times

Last updated: Feb 09 '23