Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a Map in ES6/ES2015 similar to an Object expression?

What is the equivalent of

var object = {   'foo': 'bar',   1: 42 } 

using an ES6 Map?

like image 979
Dan Dascalescu Avatar asked Oct 01 '15 00:10

Dan Dascalescu


People also ask

How do I initialize a node js Map?

To initialize a Map with values, use the Map() constructor, passing it an array containing nested arrays of key-value pairs, where the first element in the array is the key and the second - the value. Each key-value pair is added to the new Map .

Is Map and object same in JavaScript?

Map is a data structure which helps in storing the data in the form of pairs. The pair consists of a unique key and a value mapped to the key. It helps prevent duplicity. Object follows the same concept as that of map i.e. using key-value pair for storing data.

Can we convert Map to object in JavaScript?

To convert a Map to an object, call the Object. fromEntries() method passing it the Map as a parameter, e.g. const obj = Object. fromEntries(map) . The Object.

How do I use the Map function in ES6?

ES6 - Array Method map()map() method creates a new array with the results of calling a provided function on every element in this array.


2 Answers

The closest you can get is:

let object = new Map([   ['foo', 'bar'],   ['1', 42] ]); 

Important things to notice:

  1. Object properties are identified by strings, while Map keys can be any value, so make sure all keys are strings in the input array.
  2. Iterating a Map object yields entries by insertion order. That is not guaranteed for objects, so behavior might be different.
like image 65
Amit Avatar answered Nov 07 '22 21:11

Amit


In modern browsers it can be as simple as:

new Map(Object.entries(object)) 
like image 20
Dimitris Avatar answered Nov 07 '22 22:11

Dimitris