Check out our Angular Book Series.

How do I get an Array of all the Keys in a JavaScript Map?

I'm working on an Angular application and want to loop over all the keys in a JavaScript map. A map is a key value pair data type, like an object, but geared for dynamic properties. In the ColdFusion world we called this a structure, and in ActionScript we called it a dictionary, but the concept is the same.

I can create a map and add items to it, like this:


let myMap = new Map();
myMap.set('foo', 'bar');
myMap.set('bar', 'Barbar');
myMap.set('foobar', 'BarbarFooFoo');

You can look at the map like this:

Once it has a set of keys, I can get the keys using this:


myMap.keys();

This is an object, or more specifically an iterator. But, I want the keys as an array.

One trick is to convert the iterator to an array using Array.from():


Array.from( hydratedImageMap.keys() );

A more 'ES6' technique would be to use the spread operator:


[ ...hydratedImageMap.keys() ]

You'll see similar output:

Not all that hard! Get the code here or play with it here.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.