Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Array Map Return Object

Tags:

typescript

People also ask

Can maps return objects?

. 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.

What does .map return TypeScript?

Return Value: This method returns the created array. Below examples illustrate the Array map() method in TypeScript.

How do you map an array to an object?

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.