我想开始使用ES6地图而不是JS对象,但我被阻止了,因为我不知道如何JSON.stringify()一个地图。我的键保证是字符串,我的值总是会被列出。我真的必须写一个包装器方法来序列化吗?
当前回答
下面的方法将Map转换为JSON字符串:
public static getJSONObj(): string {
return JSON.stringify(Object.fromEntries(map));
}
例子:
const x = new Map();
x.set("SomeBool", true);
x.set("number1", 1);
x.set("anObj", { name: "joe", age: 22, isAlive: true });
const json = getJSONObj(x);
// Output:
// '{"SomeBool":true,"number1":1,"anObj":{"name":"joe","age":222,"isAlive":true}}'
其他回答
下面的方法将Map转换为JSON字符串:
public static getJSONObj(): string {
return JSON.stringify(Object.fromEntries(map));
}
例子:
const x = new Map();
x.set("SomeBool", true);
x.set("number1", 1);
x.set("anObj", { name: "joe", age: 22, isAlive: true });
const json = getJSONObj(x);
// Output:
// '{"SomeBool":true,"number1":1,"anObj":{"name":"joe","age":222,"isAlive":true}}'
鉴于您的示例是一个简单的用例,其中键将是简单类型,我认为这是JSON stringify Map的最简单方法。
JSON.stringify(Object.fromEntries(map));
我认为Map的底层数据结构是键值对数组(数组本身)。就像这样:
const myMap = new Map([
["key1", "value1"],
["key2", "value2"],
["key3", "value3"]
]);
因为底层的数据结构就是我们在Object中找到的。条目,我们可以在Map上使用Object.fromEntries()的原生JavaScript方法,就像在数组上一样:
Object.fromEntries(myMap);
/*
{
key1: "value1",
key2: "value2",
key3: "value3"
}
*/
然后剩下的就是对结果使用JSON.stringify()。
尽管在某些情况下,如果你是地图的创建者,你会在一个单独的“src”文件中编写代码,并将副本保存为.txt文件,如果写得足够简洁,可以很容易地读取、破译并添加到服务器端。
然后,新文件将被保存为.js文件,并从服务器发回对该文件的引用。一旦作为JS读入,该文件将完美地重构自身。美妙之处在于重构时不需要笨拙的迭代或解析。
只是想分享我的Map和Set JSON版本。stringify。 我正在对它们进行排序,对调试有用……
function replacer(key, value) {
if (value instanceof Map) {
const reducer = (obj, mapKey) => {
obj[mapKey] = value.get(mapKey);
return obj;
};
return [...value.keys()].sort().reduce(reducer, {});
} else if (value instanceof Set) {
return [...value].sort();
}
return value;
}
用法:
const map = new Map();
const numbers= new Set()
numbers.add(3);
numbers.add(2);
numbers.add(3);
numbers.add(1);
const chars= new Set()
chars.add('b')
chars.add('a')
chars.add('a')
map.set("numbers",numbers)
map.set("chars",chars)
console.log(JSON.stringify(map, replacer, 2));
结果:
{
"chars": [
"a",
"b"
],
"numbers": [
1,
2,
3
]
}
Stringify Map实例(对象作为键是可以的):
JSON.stringify([...map])
or
JSON.stringify(Array.from(map))
or
JSON.stringify(Array.from(map.entries()))
输出格式:
// [["key1","value1"],["key2","value2"]]