. map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array. This modification is done based on what is returned in the callback function.
Return Value: This method returns the created array. Below examples illustrate the Array map() method in TypeScript.
To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.
If you put it in parenthesis the compiler will treat it as an object literal not a code block:
array.map(val => ({
key1: val.key1,
key2: val.key2
}));
A type assertion also works if you have an interface for the object literal (but is not as type safe):
interface IKeys { key1: string; key2: string }
array.map(val => <IKeys>{
key1: val.key1,
key2: val.key2
});
As an update to @Titian Cernicova-Dragomir's answer above, it's worth mentioning the as
operator (for Type Assertion), especially useful when working with React's TSX(JSX) files, equivalent to the <Type>
syntax:
interface IKeys { key1: string; key2: string }
// notice the parentheses, to avoid confusion with a block scope
array.map(val => ({
key1: val.key1,
key2: val.key2
} as IKeys));
It was introduced because the angle brackets syntax (<ComponentOrElement>
) is reserved for components / JSX Elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With