我想开始使用ES6地图而不是JS对象,但我被阻止了,因为我不知道如何JSON.stringify()一个地图。我的键保证是字符串,我的值总是会被列出。我真的必须写一个包装器方法来序列化吗?


当前回答

不能调用JSON。在Map或Set上进行stringify。

您将需要转换:

使用Object. fromentries或 使用展开运算符[…]

在调用JSON.stringify之前

Map

常量 obj = {'Key1': 'Value1', 'Key2': 'Value2'}, map = new map (Object.entries(obj)); 地图。设置(“Key3”、“Value3”);//添加一个新条目 //不显示键值对 console.log(地图:,JSON.stringify(地图)); //显示键值对 console.log(JSON.stringify(Object.fromEntries(map), null, 2)); .as-console-wrapper {top: 0;Max-height: 100%重要;}

Set

常量 arr = ['Value1', 'Value2'], set = new set (arr); set.add(“Value3”);//添加一个新项目 //不显示值 console.log (': ', JSON.stringify(集)); //显示值 console.log (JSON.stringify([…Set], null, 2)); .as-console-wrapper {top: 0;Max-height: 100%重要;}

toJSON方法

如果你想调用JSON。如果在类对象上使用stringify,则需要重写toJSON方法以返回实例数据。

class Cat { constructor(options = {}) { this.name = options.name ?? ''; this.age = options.age ?? 0; } toString() { return `[Cat name="${this.name}", age="${this.age}"]` } toJSON() { return { name: this.name, age: this.age }; } static fromObject(obj) { const { name, age } = obj ?? {}; return new Cat({ name, age }); } } /* * JSON Set adds the missing methods: * - toJSON * - toString */ class JSONSet extends Set { constructor(values) { super(values) } toString() { return super .toString() .replace(']', ` ${[...this].map(v => v.toString()) .join(', ')}]`); } toJSON() { return [...this]; } } const cats = new JSONSet([ Cat.fromObject({ name: 'Furball', age: 2 }), Cat.fromObject({ name: 'Artemis', age: 5 }) ]); console.log(cats.toString()); console.log(JSON.stringify(cats, null, 2)); .as-console-wrapper { top: 0; max-height: 100% !important; }

其他回答

虽然ecmascript还没有提供方法,但这仍然可以使用JSON来完成。如果将map映射到JavaScript原语,则使用stingify。下面是我们将使用的Map示例。

const map = new Map();
map.set('foo', 'bar');
map.set('baz', 'quz');

转到JavaScript对象

你可以用下面的辅助函数转换成JavaScript对象文字。

const mapToObj = m => {
  return Array.from(m).reduce((obj, [key, value]) => {
    obj[key] = value;
    return obj;
  }, {});
};

JSON.stringify(mapToObj(map)); // '{"foo":"bar","baz":"quz"}'

转到JavaScript对象数组

这个函数的辅助函数将更加紧凑

const mapToAoO = m => {
  return Array.from(m).map( ([k,v]) => {return {[k]:v}} );
};

JSON.stringify(mapToAoO(map)); // '[{"foo":"bar"},{"baz":"quz"}]'

进入数组的数组

这个更简单,你可以用

JSON.stringify( Array.from(map) ); // '[["foo","bar"],["baz","quz"]]'

下面的方法将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}}'

Stringify Map实例(对象作为键是可以的):

JSON.stringify([...map])

or

JSON.stringify(Array.from(map))

or

JSON.stringify(Array.from(map.entries()))

输出格式:

// [["key1","value1"],["key2","value2"]]

下面的解决方案工作,即使你有嵌套的地图

function stringifyMap(myMap) {
    function selfIterator(map) {
        return Array.from(map).reduce((acc, [key, value]) => {
            if (value instanceof Map) {
                acc[key] = selfIterator(value);
            } else {
                acc[key] = value;
            }

            return acc;
        }, {})
    }

    const res = selfIterator(myMap)
    return JSON.stringify(res);
}

使用spread sytax Map可以在一行中序列化:

JSON.stringify([...new Map()]);

并反序列化它:

let map = new Map(JSON.parse(map));