简体   繁体   中英

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",
   }
]

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); 

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); 

You can also 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 myMap = new Map().set('a', 1).set('b', 2);
const arr = [];

myMap.forEach((value, name) => arr.push({ name, value }));

console.log(arr);

Or, as an alternative, you may use the for...of loop like so:

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

for (const [name, value] of myMap) {
    arr.push({ name, value });
}

console.log(arr);

Wrote a blog post explaining different methods for those who're interested in learning more.

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})

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); 

With ES6 Spread syntax only:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM