xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-02-22 17:05  xgqfrms  阅读(270)  评论(5编辑  收藏  举报