Ole
Ole

Reputation: 47058

Get JavaScript Map values as array?

Is there like a quick way to get Javascript Map values as an array?

const map:Map<number, string> = new Map()
map.set(1, '1')
map.set(2, '2')

And then something like Array.from(map.values()) would give ['1','2'] ... I could have sworn that I've something like this...?

Upvotes: 16

Views: 23739

Answers (2)

Penny Liu
Penny Liu

Reputation: 17458

Another alternative could be using Spread syntax (...).

const map = new Map().set(4, '4').set(2, '2');
console.log([...map.values()]);

Upvotes: 11

Nina Scholz
Nina Scholz

Reputation: 386670

It is working fine. Array.from can take an iterable value as well.

const map = new Map;

map.set(1, '1');
map.set(2, '2');

console.log(Array.from(map.values()));

Upvotes: 25

Related Questions