Creating an array of objects using class in Typescript

I’m working on re-engineering this persons code: https://stackblitz.com/edit/angular-sx79hu?embed=1&file=app/multiselect-autocomplete-example.html

So i have a User class:

export class User {
  constructor(public code: string, public description: string, public selected: boolean ) {
    if (selected === undefined) selected = false;
  }
}

and I have another array (NewArray) that I am going to receive via service. It will be an array of objects with ‘i’ number of elements, each object with props {“prop1″:”value1”, “prop2″:”value2”}

I’m trying to create a new Array called Users which will use the User class like so BUT will get the elements by looping through NewArray:

 users = [new User('i.prop1','i.prop2', false)]

but I only get the last index instead of all from 0 to i.

What am I missing here? Thanks!

Answer

you need to use something like below. Check and let me know if it works.

users = [];
newArray.forEach((item, i) => {
    users.push(new User( item.prop1, item.prop2, false));
}):

Leave a Reply

Your email address will not be published. Required fields are marked *