Eugene Sukh
Eugene Sukh

Reputation: 2727

Map one array to another Typescript

I have 2 arrays that has different Models

here is model of first array

export class TenancyTenantDto  {
name!: string | undefined;
email!: string | undefined;
paymentMethodName!: string | undefined;
paymentMethodId!: number | undefined;
propertyTenantId!: number | undefined;
isPrimary!: boolean | undefined;
id!: number | undefined;
}

and second array model

 export class TenancyTenantViewModel {
    name: string;
    email: string;
    paymentMethodName: string;
    paymentMethodId: number;
    tenancyTenantId: number;
    tenantId: number;
    isPrimary: boolean;
    id: Guid;


}

I need to map 1 array to 2. How I can do it?

I tried to do it like this this.tenants = [...tenants.map(e => new TenancyTenantViewModel({id: e.id, etc.}))];

but seems it not works.

Upvotes: 1

Views: 161

Answers (1)

mamichels
mamichels

Reputation: 639

Define your map:

function mapType(source: TenancyTenantDto): TenancyTenantViewModel {
     return { // Your mapping logic here }
}

Usage:

const originalArray: TenancyTenantDto[] = [...]
const mappedArray: TenancyTenantViewModel[] = originalArray.map(mapType); 

Upvotes: 1

Related Questions