如何将普通对象转换为 ES6 Map? [英] How to convert a plain object into an ES6 Map?
问题描述
出于某种原因,我在 MDN 文档中找不到这个简单的东西(也许我只是想念它).
For some reason I can't find this simple thing in the MDN docs (maybe I'm just missing it).
我希望这能奏效:
const map = new Map({foo: 'bar'});
map.get('foo'); // 'bar'
...但第一行抛出 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?
推荐答案
是的,Map
构造函数采用键值对数组.
Yes, the Map
constructor takes an array of key-value pairs.
Object.entries
是 ES2017 (19.1.2.5).
const map = new Map(Object.entries({foo: 'bar'}));
map.get('foo'); // 'bar'
目前已在 Firefox 46+ 和 Edge 14+ 及更新版本中实现Chrome 版本
如果您需要支持较旧的环境并且转译不适合您,请使用 polyfill,例如 georg 推荐的:
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]]);
这篇关于如何将普通对象转换为 ES6 Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!