Back to the lesson

Iterable keys

importance: 5

We want to get an array of map.keys() and go on working with it (apart from the map itself).

But there’s a problem:

let map = new Map();

map.set("name", "John");

let keys = map.keys();

// Error: numbers.push is not a function
keys.push("more");

Why? How can we fix the code to make keys.push work?

That’s because map.keys() returns an iterable, but not an array.

We can convert it into an array using Array.from:

let map = new Map();

map.set("name", "John");

let keys = Array.from(map.keys());

keys.push("more");

alert(keys); // name, more