Mohit Sharma
Mohit Sharma

Reputation: 175

Get Only Values from a Map to an array

I want to get values of a map and store inside a string array in typescript.

myMap= [0:'Mohit',1:'Balesh',2:'Jatin'];
arr[];

Expected Result arr['Mohit','Balesh','Jatin']

Upvotes: 13

Views: 29829

Answers (3)

anilam
anilam

Reputation: 892

Map.values() returns a MapIterator object which can be converted to Array using Array.from:

let values = Array.from( myMap.values() );
// ["a", "b"]

Upvotes: 7

Fred Liebenberg
Fred Liebenberg

Reputation: 161

To get an array from the values in a map you can spread the map values into an array using the Javascript spread operator (...) with the values() method of map.

yourArray = [...myMap.values()]

// gives the array ['Mohit', 'Balesh', 'Jatin']

Upvotes: 15

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10147

First of all, your myMap is not valid. It should look like this:

myMap= {0:'Mohit',1:'Balesh',2:'Jatin'};

And getting an array from it should look like this:

myArr = Object.values(myMap);

Upvotes: 7

Related Questions