The map() method is helpful to creates a new array with the results of calling a provided function on every element in the calling array.

Suppose that we have two classes:

export class OriginalType
{ public id: number; public name: string;
} export class DestinationType
{ public info: string;
}

And we have an Angular service called ‘myService‘ that through a .getObjects() method returns the following data:

result: OriginalType = [ 
{ id: 1, name:'Ross'}, 
{ id: 2, name:'Kevin'}, 
{ id: 3, name:'Alan'},
];

If we need to fill a DestinationType array from the service result (that is an OriginalType) with the values id and name joined into the info property, we can use the .map() method of the Array prototype to do this, like in the following example:

// myService declaration omitted because outside the scope of this post private mapOperations()
{ // Call the promise method that returns an OriginalType collection this.myService.getObjects().then(result => { // Fill the DestinationType array with .map method let newType= result.map((a: OriginalType) => { let b = new DestinationType(); b.info = a.id.toString() + '-' + a.name; return b; }); console.log(newType); // expected output: Array ['1-Ross', '2-Kevin', '3-Alan'] });
}

Laisser un commentaire