In JavaScript, you can store key/value pairs in a Map
while remembering the original order of insertion of each key.
For example, the code below creates a groceriesMap
variable holding a Map
object with the names of fruits and vegetables as the keys and their weight as the values:
groceriesMap = new Map();
groceriesMap.set('tomatoes', 500);
groceriesMap.set('cucumbers', 250);
groceriesMap.set('peppers', 250);
If you were to read the contents of the newly-created groceriesMap
variable, you would see the following object:
Holding these values in a Map
object is useful for many reasons. But what if, for the purposes of your application, you need them in an array instead?
This guide will show you how to convert Map
values to an Array
in JavaScript.
How to Convert Map Keys to an Array
To convert Map values to an Array, use the Array.from
method to create a new array. Then store the keys in the newly-created array object using the Map.prototype.keys
method.
Here’s what this looks like in terms of code:
groceriesArray = Array.from(groceriesMap.keys());
And here’s what you would see if you were to read the contents of the newly-created Array
:
How to Convert Map Values to an Array
To convert Map values to an Array, use the Array.from
method to create a new array. Then store the values in the newly-created array object using the Map.prototype.values
method.
Here’s what this looks like in terms of code:
groceriesArray = Array.from(groceriesMap.values());
And here’s what you would see if you were to read the contents of the newly-created Array
:
How to Convert a Map’s Key/Value Pairs to an Array of Objects
To convert a Map
object’s key/value pairs to an Array
of objects, use the Array.from
method to create a new array. Then use an arrow function to store each key/value pair in that array:
groceriesArray = Array.from(groceriesMap, ([name, value]) => ({ name, value }));
And here’s what you would see if you were to read the contents of the newly-created Array
of objects:
This helped me a lot!!
Thank you!