Nikhil Shrestha
Nikhil Shrestha

Reputation: 1540

How to convert Map to array of object?

i'm trying to convert a Map into array of object

Lets say I have the following map:

let myMap = new Map().set('a', 1).set('b', 2);

And I want to convert the above map into the following:

[
   {
      "name": "a",
      "value": "1",
   },
   {
      "name": "b",
      "value": "2",
   }
]

Upvotes: 125

Views: 226226

Answers (7)

Bippan Kumar
Bippan Kumar

Reputation: 718

let map = new Map().set('a', 1).set('b', 2),
array = Array.from(map.values());
console.log(array);

Upvotes: 7

devs jfh
devs jfh

Reputation: 11

You'll got : [ { key: 'a', value: 1 }, { key: 'b', value: 2 } ]

if instead, you use the following line :

    const arr = [...map ].map(([key, value]) => ([key]: value}));

You will have the following result : [ {a: 1}, {b: 2} ]

Upvotes: -1

Teocci
Teocci

Reputation: 8835

Very simple I will explain in steps:

  1. Spread a map into an array of arrays.
const map = new Map().set('a', 1).set('b', 2).set('c', 3)
const mapArr = [...map] // array of arrays
  1. Map each subarray as key-value pairs. map function returns a new array containing object of key-value pairs.
const arr = mapArr.map(([key, value]) => ({key, value}))

** Remember: ** the name we use for mapping the data will be the name of the object mapped in this case key and value.

One liner:

const map = new Map().set('a', 1).set('b', 2).set('c', 3)
const arr = [...map ].map(([key, value]) => ({key, value}))
console.log({arr})

Upvotes: 5

Houcine Adsens
Houcine Adsens

Reputation: 27

With ES6 Spread syntax only :

const myMap = new Map().set('a', 1).set('b', 2);
const arr = [...myMap];
console.log(arr);

Upvotes: 0

Fraction
Fraction

Reputation: 12954

Use Spread syntax and Array.map():

let myMap = new Map().set('a', 1).set('b', 2);

const arr = [...myMap].map(([name, value]) => ({ name, value }));

console.log(arr);

Upvotes: 58

Ghoul Ahmed
Ghoul Ahmed

Reputation: 4806

with spread of ES6 like this:

let myMap = new Map().set('a', 1).set('b', 2);

const  result = Array.from(myMap).map(([name, value]) => ({name, value}))

console.log(result);

Upvotes: 10

Nina Scholz
Nina Scholz

Reputation: 386522

You could take Array.from and map the key/value pairs.

let map = new Map().set('a', 1).set('b', 2),
    array = Array.from(map, ([name, value]) => ({ name, value }));

console.log(array);

Upvotes: 199

Related Questions