EdwardZZZ / articles

工作点滴记录
2 stars 0 forks source link

JSON #69

Open EdwardZZZ opened 4 years ago

EdwardZZZ commented 4 years ago
function map2JSON(obj) {
    if (obj instanceof Set) return [...obj];

    if (obj instanceof Map) {
        const newOjb = {};
        for (const key of obj.keys()) {
            const val = obj.get(key);
            newOjb[key] = typeof val === 'object' ? map2JSON(val) : val;
        }
        return newOjb;
    }

    if (Object.prototype.toString.call(obj).slice(8, -1) === 'Object') {
        const newOjb = {};
        for (const key of Reflect.ownKeys(obj)) {
            const val = obj[key];
            newOjb[key] = typeof val === 'object' ? map2JSON(val) : val;
        }
        return newOjb;
    }

    if (Object.prototype.toString.call(obj).slice(8, -1) === 'Array') {
        const newOjb = [];
        for (const key of Reflect.ownKeys(obj)) {
            const val = obj[key];
            newOjb[key] = typeof val === 'object' ? map2JSON(val) : val;
        }
        return newOjb;
    }

    return obj;
}
EdwardZZZ commented 4 years ago
const obj = {
    a: 1,
    b: 2,
    c: 3,
    d: new Map([
        ['a', 1],
        ['b', 2]
    ]),
    e: new Set(['a', 'b', 'c', 'd']),
}

const type = (obj) => Object.prototype.toString.call(obj).slice(8, -1);

const format = () => {
    const set = new WeakSet();

    return (key, value) => {
        if (set.has(value)) {
            retrun `Circle *${key}`;
        }

        if (typeof value === 'object') set.add(value);

        if (type(value) === 'Map') {
            const mapObj = {};
            for (const [k, v] of value) {
                if (typeof k === 'object') {
                    console.log(`Cann't stringify Map's 'Object' key.`);
                    continue;
                }

                mapObj[k] = v;
            }

            // return `Map => ${JSON.stringify(mapObj)}`;
            return {'Map =>': mapObj};
        }

        if (type(value) === 'Set') {
            // return `Set => ${JSON.stringify([...value])}`;
            return {'Set =>': [...value]};
        }

        return value;
    }
}

const stringify = JSON.stringify;
JSON.stringify = (obj, replacer = format(), space = 4) => {
    return stringify.call(JSON, obj, replacer, space);
}

console.log(JSON.stringify(obj));