localStorage & Map All In One
localStorage & Map All In One
JSON.stringify & JSON.parse
const xyzMap = new Map([[1, 'map testing 1'], [2, 'map testing 2']]);
// Map(2) {1 => "map testing 1", 2 => "map testing 2"}
localStorage.setItem('xyzMap', JSON.stringify([...xyzMap]));
// undefined
localStorage.getItem('xyzMap');
// "[[1,"map testing 1"],[2,"map testing 2"]]"
// ✅
abcMap = new Map(JSON.parse(localStorage.getItem('xyzMap')));
// Map(2) {1 => "map testing 1", 2 => "map testing 2"}
demos
js localStorage & Map All In One
(() => {
// bug
const map = new Map();
map.set(1, {id: 1, name: 'eric'});
// Map(1) {1 => {…}}
localStorage.setItem('app', map);
// undefined
localStorage.getItem('app');
// "[object Map]" ❌
})();
(() => {
// ok
const map = new Map();
map.set(1, {id: 1, name: 'eric'});
// Map(1) {1 => {…}}
localStorage.setItem('app', JSON.stringify([...map]));
// undefined
const newMap = new Map(JSON.parse(localStorage.getItem('app')));
// Map(1) {1 => {…}} ✅
})();
refs
https://gist.github.com/xgqfrms/b203a103619b1858e68446dcbc22dc8a
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/14431425.html
未经授权禁止转载,违者必究!