0

I have an array. I want to dynamically generate new class instances from an array.

class Test{
  constructor(name){
    this.name = name;
  }
  getName(){
    return this.name;
  }
}

let myArray = [ "instance1", "instance2", "instance3" ];

I want a result like this:

let myArray[i] = new Test;

myArray[i].getName();
1
  • Welcome! Your class in not well-defined ({} missing from constructor, for one). Look into Classes. Second value of myArry is not closed (with'). Did you want only element i of the array to be an instance of the class, or all the elements of the array? Commented Nov 6, 2020 at 15:09

1 Answer 1

1

Basically you just need to call Array.protype.map on the array, and as your callback function you use an arrow function to create a new Test from the array value.

class Test {
  constructor(name) {
    this.name = name;
  }
  getName() {
    return this.name;
  }
}

const names = ['instance1','instance2','instance3'];
const instances = names.map( name => new Test(name) );

console.log( instances[1].getName() ); // logs 'instance2'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.