To convert an object to a Map , call the Object. entries() method to get an array of key-value pairs and pass the result to the Map() constructor, e.g. const map = new Map(Object. entries(obj)) . The new Map will contain all of the object's key-value pairs.
To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.
To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .
Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON. parse('{"name":"John", "age":30, "city":"New York"}');
Yes, the Map
constructor takes an array of key-value pairs.
Object.entries
is a new Object static method available in ES2017 (19.1.2.5).
const map = new Map(Object.entries({foo: 'bar'}));
map.get('foo'); // 'bar'
It's currently implemented in Firefox 46+ and Edge 14+ and newer versions of Chrome
If you need to support older environments and transpilation is not an option for you, use a polyfill, such as the one recommended by georg:
Object.entries = typeof Object.entries === 'function' ? Object.entries : obj => Object.keys(obj).map(k => [k, obj[k]]);
Do I really have to first convert it into an array of arrays of key-value pairs?
No, an iterator of key-value pair arrays is enough. You can use the following to avoid creating the intermediate array:
function* entries(obj) {
for (let key in obj)
yield [key, obj[key]];
}
const map = new Map(entries({foo: 'bar'}));
map.get('foo'); // 'bar'
The answer by Nils describes how to convert objects to maps, which I found very useful. However, the OP was also wondering where this information is in the MDN docs. While it may not have been there when the question was originally asked, it is now on the MDN page for Object.entries() under the heading Converting an Object to a Map which states:
Converting an Object to a Map
The
new Map()
constructor accepts an iterable ofentries
. WithObject.entries
, you can easily convert fromObject
toMap
:const obj = { foo: 'bar', baz: 42 }; const map = new Map(Object.entries(obj)); console.log(map); // Map { foo: "bar", baz: 42 }
ES6
convert object to map:
const objToMap = (o) => new Map(Object.entries(o));
convert map to object:
const mapToObj = (m) => [...m].reduce( (o,v)=>{ o[v[0]] = v[1]; return o; },{} )
Note: the mapToObj function assumes map keys are strings (will fail otherwise)
const myMap = new Map(
Object
.keys(myObj)
.map(
key => [key, myObj[key]]
)
)
Alternatively you can use the lodash toPairs method:
const _ = require('lodash');
const map = new Map(_.toPairs({foo: 'bar'}));
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