1. Map转换JSON:

使用 Object.fromEntries() 方法将Map转为对象;

const map = new Map([
  ['name', '张三'],
  ['age', '18'],
  ['address', 'xian'],
]);
const json = Object.fromEntries(map);
console.log(json);
// {"name":"张三","age":"18","address":"xian"}

JSON.stringify() 是将对象转为json字符串;

const map = new Map([
  ['name', '张三'],
  ['age', '18'],
  ['address', 'xian'],
]);
const json = JSON.stringify(Object.fromEntries(map));
console.log(json);
// '{"name":"张三","age":"18","address":"xian"}'

2. JSON转换Map

如果是JSON字符串必须使用JSON.parse()转为对象;

使用 Object.entries() 接受对象返回二维数组;

let arr = Object.entries({"name":"张三","age":"18","address":"xian"});
console.log(arr)
// [["name","张三"],["age","18"],["address","xian"]]

调用Map()构造函数

let arr = Object.entries({"name":"张三","age":"18","address":"xian"});
let map = new Map(arr);
console.log(map);
// {'name' => '张三', 'age' => '18', 'address' => 'xian'}

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐