Languages
[Edit]
EN

JavaScript - convert Map to array of objects

0 points
Created by:
nickkk0
647

In this article, we would like to show you how to convert a Map to an array of objects in JavaScript.

Quick solution:

const arrayFromMap = Array.from(myMap, ([key, value]) => ({ key, value }));

 

Practical example

In this example, we use the Array.from() method to map the key/value pairs from the Map object into an array.

// ONLINE-RUNNER:browser;

const myMap = new Map([
    [1, 'A'],
    [2, 'B'],
    [3, 'C'],
]);

const myArray = Array.from(myMap, ([key, value]) => ({ key, value }));

console.log(JSON.stringify(myArray, null, 4));

Output:

[
  { key: 1, value: 'A' },
  { key: 2, value: 'B' },
  { key: 3, value: 'C' }
]

References

  1. Array.from() - JavaScript | MDN
  2. Map - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join