你如何 JSON.stringify 一个 ES6 Map? [英] How do you JSON.stringify an ES6 Map?

查看:44
本文介绍了你如何 JSON.stringify 一个 ES6 Map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想开始使用 ES6 Map 而不是 JS 对象,但我被阻止了,因为我无法弄清楚如何 JSON.stringify() 一个 Map.我的键保证是字符串,我的值将始终被列出.我真的必须写一个包装方法来序列化吗?

I'd like to start using ES6 Map instead of JS objects but I'm being held back because I can't figure out how to JSON.stringify() a Map. My keys are guaranteed to be strings and my values will always be listed. Do I really have to write a wrapper method to serialize?

推荐答案

JSON.stringifyJSON.parse 都支持第二个参数.replacerreviver 分别.使用下面的替换器和恢复器,可以添加对原生 Map 对象的支持,包括深度嵌套的值

Both JSON.stringify and JSON.parse support a second argument. replacer and reviver respectively. With replacer and reviver below it's possible to add support for native Map object, including deeply nested values

function replacer(key, value) {
  if(value instanceof Map) {
    return {
      dataType: 'Map',
      value: Array.from(value.entries()), // or with spread: value: [...value]
    };
  } else {
    return value;
  }
}

function reviver(key, value) {
  if(typeof value === 'object' && value !== null) {
    if (value.dataType === 'Map') {
      return new Map(value.value);
    }
  }
  return value;
}

用法:

const originalValue = new Map([['a', 1]]);
const str = JSON.stringify(originalValue, replacer);
const newValue = JSON.parse(str, reviver);
console.log(originalValue, newValue);

结合数组、对象和映射的深度嵌套

Deep nesting with combination of Arrays, Objects and Maps

const originalValue = [
  new Map([['a', {
    b: {
      c: new Map([['d', 'text']])
    }
  }]])
];
const str = JSON.stringify(originalValue, replacer);
const newValue = JSON.parse(str, reviver);
console.log(originalValue, newValue);

这篇关于你如何 JSON.stringify 一个 ES6 Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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