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

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

问题描述

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); 只是返回 '{}',这意味着 a 在恢复时变成了一个空对象.

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

我发现 es6-mapify 允许在 Map 和一个普通对象,所以这可能是一种解决方案,但我希望我需要诉诸外部依赖来保持我的地图.

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

应该可以.对于相反的情况,使用

should work. For the reverse, use

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

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

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