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'}
————————————————
版权声明:本文为CSDN博主「dong914」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_63572193/article/details/127774422
0条评论
点击登录参与评论