Monday, May 20, 2024
74
rated 0 times [  77] [ 3]  / answers: 1 / hits: 177412  / 8 Years ago, fri, april 15, 2016, 12:00:00

For some reason I can't find this simple thing in the MDN docs (maybe I'm just missing it).



I expected this to work:



const map = new Map({foo: 'bar'});

map.get('foo'); // 'bar'


...but the first line throws TypeError: (var)[Symbol.iterator] is not a function



How do I make a Map from a plain object? Do I really have to first convert it into an array of arrays of key-value pairs?


More From » ecmascript-6

 Answers
11

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

[#62538] Thursday, April 14, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stephonkeandrer

Total Points: 392
Total Questions: 94
Total Answers: 100

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
;