- How to Convert JavaScript Map to Array of Objects?
- Using Array.from()
- Using the Spread Operator With Array.prototype.map()
- Iterating Over Map and Adding Elements to Array
- Convert map to array javascript
- # Convert a Map to an Array of Objects in JavaScript
- # Convert a Map to an Array of Objects using Array.map()
- # Convert a Map to an Array of Objects using Map.forEach()
- # Convert a Map to an Array of Objects using for. of
- # Additional Resources
- How to convert Map Values to an Array in JavaScript
- The solution
- Conclusion
How to Convert JavaScript Map to Array of Objects?
Let’s suppose you have the following JavaScript Map object:
const myMap = new Map(); myMap.set('foo', 1); myMap.set('bar', 2); myMap.set('baz', 3);
To convert it into an array of objects, for example, like so:
You can do any of the following:
Using Array.from()
Since Array.from() works on iterables such as Map , you can simply pass it as an argument to Array.from() . This would result in an array of arrays containing key and value from the Map . To illustrate this, consider for example, the following:
const arr = Array.from(myMap); console.log(arr); // [['foo', 1], ['bar', 2], ['baz', 3]]
To transform this array of arrays into an array of objects, you can simply pass a map function as the second (optional) argument to Array.from() which will be called on every element of the array. For example:
const arr = Array.from(myMap, function (item) < return < key: item[0], value: item[1] >>); console.log(arr); /* [ , , , ] */
You can shorten the map function to a one-liner by using; an arrow function, and destructing syntax in the callback function argument, like so:
const arr = Array.from(myMap, (Convert map to array javascript) => (< key, value >)); console.log(arr); /* [ , , , ] */
Using the Spread Operator With Array.prototype.map()
You can use the spread operator on Map to unpack its elements into an array, for example, like so:
const arr = [. myMap]; console.log(arr); // [['foo', 1], ['bar', 2], ['baz', 3]]
As you can see, this results in an array of arrays containing key and value from the Map object. To transform this into an array of objects instead, you can call the Array.prototype.map() method on the resulting array, for example, in the following way:
const arr = [. myMap].map(function (item) < return < key: item[0], value: item[1] >>); console.log(arr); /* [ , , , ] */
You can shorten the map function to a one-liner by using; an arrow function, and destructing syntax in the callback function argument, like so:
const arr = [. myMap].map((Convert map to array javascript) => (< key, value >)); console.log(arr); /* [ , , , ] */
Iterating Over Map and Adding Elements to Array
You can simply iterate over the Map object using any compatible iteration method and add each item as an object to the resulting array.
For example, you can use Map.prototype.forEach() in the following way:
const arr = []; myMap.forEach((value, key) => arr.push(< key, value >)); console.log(arr); /* [ , , , ] */
Or, alternatively, you may use the for. of loop like so:
const arr = []; for (const Convert map to array javascript of myMap) < arr.push(< key, value >); > console.log(arr); /* [ , , , ] */
Hope you found this post useful. It was published 29 Sep, 2021 . Please show your love and support by sharing this post.
Convert map to array javascript
Last updated: Dec 29, 2022
Reading time · 4 min
# Convert a Map to an Array of Objects in JavaScript
To convert a Map to an array of objects:
- Pass the Map and a function to the Array.from() method.
- Iterate over the Map in the function and return an object containing the current key-value pair.
- The Array.from() method will convert the Map to an array of objects.
Copied!const map = new Map(); map.set('name', 'Bob'); map.set('country', 'Chile'); const arr = Array.from(map, ([key, value]) => return [key]: value>; >); // 👇️ [, ] console.log(arr);
You can format the array of objects differently depending on your use case.
Copied!const map = new Map(); map.set('name', 'Bob'); map.set('country', 'Chile'); const arr = Array.from(map, ([key, value]) => return key, value>; >); // 👇️ [ < key: 'name', value: 'Bob' >, // < key: 'country', value: 'Chile' >] console.log(arr);
We passed the following arguments to the Array.from method:
- An iterable object that we want to convert to an array.
- A map function that gets called with each element in the array.
If we call the Array.from() method without the map function, we get a two dimensional array.
Copied!const map = new Map(); map.set('name', 'Bob'); map.set('country', 'Chile'); // 👇️ [['name', 'Bob'], ['country', 'Chile']] const arr = Array.from(map); console.log(arr);
The function we passed to the Array.from() method gets called with each element in the array.
We used the square bracket [] syntax to destructure the elements of the array in the arrow function.
Copied!const [a, b] = ['hello', 'world']; console.log(a); // 👉️ hello console.log(b); // 👉️ world
Array destructuring enables us to unpack multiple array values into variables in a single statement.
Whatever we return from this function gets added to the return value of Array.from() .
This is an actual map (Array.map) function. It allows us to iterate over an array and create a new array based on the returned values.
We used the dynamic property key syntax [] to set the key of the object to the actual key of the Map .
Copied!const arr = Array.from(map, ([key, value]) => // 👇️ return [key]: value>; >);
A simple way to think about the dynamic key assignment is that we are evaluating the variable key and setting the object’s key to the result.
Copied!const a = 'name'; const obj = [a]: 'Bob', >; console.log(obj); // 👉️
Here’s an example that achieves the same result by using the Array.map() method separately.
# Convert a Map to an Array of Objects using Array.map()
This is a three-step process:
- Convert the Map to an array.
- Use the Array.map() method to iterate over the array.
- Return an object containing the key-value pair on each iteration.
Copied!const map = new Map(); map.set('name', 'Bob'); map.set('country', 'Chile'); // 👇️ [['name', 'Bob'], ['country', 'Chile']] const arr = Array.from(map); console.log(arr); // 👇️ [] const arrOfObj = arr.map(([key, value]) => return [key]: value>; >); console.log(arrOfObj);
You can format the array of objects differently depending on your use case.
Copied!const map = new Map(); map.set('name', 'Bob'); map.set('country', 'Chile'); // 👇️ [['name', 'Bob'], ['country', 'Chile']] const arr = Array.from(map); console.log(arr); // 👇️ [ < key: 'Bob' >, < key: 'Chile' >] const arrOfObj = arr.map(([key, value]) => return key: value>; >); console.log(arrOfObj);
Instead of passing the Array.map() function as a parameter to the Array.from() method, we used it separately.
Everything works in the same way as in the previous code sample, however, the code is a little less performant.
You can also use the Map.forEach() method to convert a Map to an array of objects.
# Convert a Map to an Array of Objects using Map.forEach()
This is a three-step process:
- Declare a new variable that stores an empty array.
- Use the Map.forEach() method to iterate over the Map.
- Wrap each key-value pair in an object and push the object into the array.
Copied!const map = new Map(); map.set('name', 'Bob'); map.set('country', 'Chile'); const arr = []; map.forEach((value, key) => arr.push(key, value>); >); // 👇️ [ < key: 'name', value: 'Bob' >, < key: 'country', value: 'Chile' >] console.log(arr);
The function we passed to the Map.forEach method gets called for each key-value pair in the Map object.
On each iteration, we wrap the key and value into an object and push the object into an array.
# Convert a Map to an Array of Objects using for. of
You can also use a for..of loop to achieve the same result.
Copied!const map = new Map(); map.set('name', 'Bob'); map.set('country', 'Chile'); const arr = []; for (const [key, value] of map) arr.push(key, value>); > // 👇️ [ < key: 'name', value: 'Bob' >, < key: 'country', value: 'Chile' >] console.log(arr);
The for. of statement is used to loop over iterable objects like arrays, strings, Map , Set and NodeList objects and generators .
Which approach you pick is a matter of personal preference. I’d use the Array.from() method with a map function because I find it quite direct and intuitive.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
How to convert Map Values to an Array in JavaScript
JavaScript has many lesser known yet useful features. One such feature is the Map object. Introduced as part of the ECMAScript 2015 (ES6) specification (and not to be confused with the Array.protoype.map() method), the Map object stores an ordered list of key-value pairs. Maps can be particularly useful for storing simple key-value pairs such as IDs and usernames:
const users = new Map(); users.set(«1», «user1»); users.set(«2», «user2»);
The fun part about using Maps is that the key-value pairs can be even more than just primitive values. For example, let’s say you have the same users except you’d like to store more information than just their username:
Now that we have a Map and a general understanding of its purpose, how would we go about actually retrieving the values of the Map? Specifically, how do we convert the values of the Map to an array?
The solution
JavaScript Map objects are iterable so that leaves us a few different ways to approach accessing a Map’s values. The first way may come to mind if you have not used Maps many times before. In these examples we’ll use the simpler Map from above where the values are just strings for brevity.
const result = []; users.forEach((user) => result.push(user));
In this solution, we create an array result to store the values and iterate through the Map, adding each value to the array. When iterating a JavaScript Map, each entry represents the value of that key-value pair. This is an easy solution and realistically there is nothing wrong with it. But can it be improved?
const result = Array.from(users.values());
Here we utilize a useful Map method: Map.protoype.values() . This method returns an iterator object for the values contained by the Map. Since this is just the iterator for the values, you will still need to iterate those values before you get your result. Luckily, the Array.from() method takes such an iterator object and creates a new array. This is a shallow-copied array so keep that in mind if you are using this with any objects with deeply-nested properties.
The final solution feels the most modern since it uses the ES6 spread syntax:
const result = [. users.values()];
This solution is similar to the previous one but simply spreads the values into an array rather than using the Array.from() method.
Conclusion
You now have a few different ways to convert the values of a Map to an array in JavaScript. While the Map object is not the most popular, it definitely has a place in your toolkit when it comes to creating a list of data — especially if the order matters and you want to be able to access each piece of data quickly and easily. There may be some debate about which method is the most efficient but at the end of the day it all depends on your use case and what feels the most concise and readable to you. If you have any other creative methods or thoughts on the ones used here please leave us some feedback.
Here is the full solution:
function getValuesFirstApproach(map) < const result = []; map.forEach((value) =>result.push(value)); return result; > function getValuesSecondApproach(map) < return Array.from(map.values()); >function getValuesThirdApproach(map) < return [. map.values()]; >const users = new Map(); users.set(«1», «user1»); users.set(«2», «user2»); console.log(getValuesFirstApproach(users)); console.log(getValuesSecondApproach(users)); console.log(getValuesThirdApproach(users));
The Isotropic Codex is a collection of code snippets and education for WordPress, web and WooCommerce developers.