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.
Asked: 2022-12-04 11:00:00 +0000
Seen: 12 times
Last updated: Feb 09 '23