Get Array of Values from Array of Objects in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 23, 2022

banner

Photo from Unsplash

Get Array of Values from Array of Objects in TypeScript #

Use the map() method to get an array of values from an array of objects in TypeScript, e.g. const ids = arr.map((obj) => obj.id). The map method will return a new array containing only the values that were returned from the callback function.

index.ts
const arr = [ { id: 1, language: 'TypeScript' }, { id: 2, language: 'JavaScript' }, { id: 3, language: 'TypeScript' }, ]; // 👇️ const ids: number[] const ids = arr.map((obj) => obj.id); console.log(ids); // 👉️ [1, 2, 3] // 👇️ const languages: string[] const languages = arr.map((obj) => obj.language); // 👇️ ['TypeScript, 'JavaScript', 'TypeScript'] console.log(languages);

The function we passed to the Array.map method gets called with each element (object) in the array.

The map method returns an array that contains the values you returned from the callback function.

We used an implicit return in the examples, but you can also use a function with a body and explicit return.

index.ts
const arr = [ { id: 1, language: 'TypeScript' }, { id: 2, language: 'JavaScript' }, { id: 3, language: 'TypeScript' }, ]; // 👇️ const ids: number[] const ids = arr.map((obj) => { return obj.id; }); console.log(ids); // 👉️ [1, 2, 3]

If the specific property you are accessing is not defined on some of the objects in the array, you might get some undefined values in the new array.

index.ts
const arr: { id: number; language?: string }[] = [ { id: 1, language: 'TypeScript' }, { id: 2 }, { id: 3, language: 'TypeScript' }, ]; // 👇️ const languages: (string | undefined)[] const languages = arr.map((obj) => obj.language); // 👇️ ['TypeScript, undefined, 'TypeScript'] console.log(languages);

Notice that the type of the languages variable is an array containing string or undefined values.

You can use the filter() method to remove the undefined values from the array.

index.ts
const arr: { id: number; language?: string }[] = [ { id: 1, language: 'TypeScript' }, { id: 2 }, { id: 3, language: 'TypeScript' }, ]; const languages = arr .map((obj) => obj.language) .filter((value) => { return value !== undefined; }); // 👇️ ['TypeScript, 'TypeScript'] console.log(languages);

The function we passed to the filter() method gets called with each element in the array.

The filter() method returns an array that contains only the values, for which the callback function returned a truthy value.

In the example above, these are only values that are not equal to undefined.

This way you can be sure the array in the languages variable won't have any undefined values.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.