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() 接受对象返回二维数组;文章来源:https://www.toymoban.com/news/detail-615673.html
let arr = Object.entries({"name":"张三","age":"18","address":"xian"});
console.log(arr)
// [["name","张三"],["age","18"],["address","xian"]]
调用Map()构造函数文章来源地址https://www.toymoban.com/news/detail-615673.html
let arr = Object.entries({"name":"张三","age":"18","address":"xian"});
let map = new Map(arr);
console.log(map);
// {'name' => '张三', 'age' => '18', 'address' => 'xian'}
到了这里,关于JavaScript中Map与JSON之间转换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!