如何在本地存储(或其他地方)中持有ES6 Map? [英] How do I persist a ES6 Map in localstorage (or elsewhere)?

查看:1276
本文介绍了如何在本地存储(或其他地方)中持有ES6 Map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var a = new Map([[ 'a', 1 ]]);
a.get('a') // 1

var forStorageSomewhere = JSON.stringify(a);
// Store, in my case, in localStorage.

// Later:
var a = JSON.parse(forStorageSomewhere);
a.get('a') // TypeError: undefined is not a function

不幸的是, JSON.stringify(a); 只需返回'{}',这意味着恢复时变为空对象。

Unfortunatly JSON.stringify(a); simply returns '{}', which means a becomes an empty object when restored.

我发现 es6-mapify ,允许在地图和一个简单的对象,所以这可能是一个解决方案,但我希望我需要诉诸一个外部依赖,只是坚持我的地图。

I found es6-mapify that allows up/down-casting between a Map and a plain object, so that might be one solution, but I was hoping I would need to resort to an external dependency simply to persist my map.

推荐答案

假设您的键和值都是可序列化的,

Assuming that both your keys and your values are serialisable,

localStorage.myMap = JSON.stringify(Array.from(map.entries()));

应该工作。相反,使用

map = new Map(JSON.parse(localStorage.myMap));

这篇关于如何在本地存储(或其他地方)中持有ES6 Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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