find the keys of a map in javascript

To find the keys of a Map in JavaScript, you can use the map's keys() method. This method returns a new iterator object that contains the keys for each element in the Map object in insertion order.

Here's an example of how to use the keys() method to get the keys of a Map:

index.tsx
const myMap = new Map();
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
myMap.set('key3', 'value3');

const keysArray = Array.from(myMap.keys());
console.log(keysArray);
// Output: ["key1", "key2", "key3"]
217 chars
9 lines

In the example above, we create a new Map object, add some key-value pairs to it, and then use the keys() method to get an iterator object containing the keys. We then use the Array.from() method to convert the iterator object into an array, which we can then log to the console.

Note that the keys() method returns an iterator object, not an array, so we have to use Array.from() (or another method like spread syntax) to convert it into an array.

related categories

gistlibby LogSnag