如何将普通对象转换为ES6 Map? [英] How to convert a plain object into an ES6 Map?

查看:169
本文介绍了如何将普通对象转换为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]不是一个函数

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

如何从普通对象中创建一个Map?我真的要先把它转换成一个键值对数组吗?

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 ,可以使用任何返回键/值对作为数组的迭代器,例如数组数组:

To initialize a Map, you can use any iterator that returns key/value pairs as arrays, such as an array of arrays:

const map = new Map([
    ['foo', 'bar']
]);

没有从对象到地图的内置转换,但是很容易使用 Object.keys

There's no built-in conversion from object to map, but it's easily done with Object.keys:

const map = new Map();
let obj = {foo: 'bar'};
Object.keys(obj).forEach(key => {
    map.set(key, obj[key]);
});

当然可以给自己一个worker函数来处理:

You can, of course, give yourself a worker function to handle that:

function buildMap(obj) {
    let map = new Map();
    Object.keys(obj).forEach(key => {
        map.set(key, obj[key]);
    });
    return map;
}

然后

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

或者这里有更多的l33t的外观(还是一件事吗?)版本:

Or here's a more l33t-looking (is that still a thing?) version:

function buildMap(obj) {
    return Object.keys(obj).reduce((map, key) => map.set(key, obj[key]), new Map());
}

(是, Map#set 返回地图引用,有人会认为这是 reduce abusage

(Yes, Map#set returns the map reference. Some would argue this is an abusage of reduce.)

或者我们可以真正地超越顶端的隐晦性:

Or we can really go over-the-top on obscurity:

const buildMap = o => Object.keys(o).reduce((m, k) => m.set(k, o[k]), new Map());

不,我永远不会这样做。 : - )

No, I would never do that for real. :-)

这篇关于如何将普通对象转换为ES6 Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆