What is the equivalent of
var object = { 'foo': 'bar', 1: 42 }
using an ES6 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 .
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.
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.
ES6 - Array Method map()map() method creates a new array with the results of calling a provided function on every element in this array.
The closest you can get is:
let object = new Map([ ['foo', 'bar'], ['1', 42] ]);
Important things to notice:
In modern browsers it can be as simple as:
new Map(Object.entries(object))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With