美文网首页
JSON.stringify cycle对象

JSON.stringify cycle对象

作者: 月生鄢 | 来源:发表于2019-02-26 16:51 被阅读0次

对于有循环引用的JS对象,用JSON.stringify会产生typeError。

解决办法:编写一个replacer作为stringify的第二个参数。我这里封装了一个方法,传入对象,返回Json字符,代码如下:

function cycleObjectToJSON(o) {
    var cache = [];
    return JSON.stringify(o, function(key, value) {
        if(['form','dialog'].includes(key)) {return;}
        if (typeof value === "object" && value !== null) {
            if (cache.indexOf(value) !== -1) {
                // Duplicate reference found
                try {
                    // If this value does not reference a parent it can be deduped
                    return JSON.parse(JSON.stringify(value));
                } catch (error) {
                    // discard key if value cannot be deduped
                    return;
                }
            }
            // Store value in our collection
            cache.push(value);
        }
        return value;
    });
}

参考资料

相关文章

网友评论

      本文标题:JSON.stringify cycle对象

      本文链接:https://www.haomeiwen.com/subject/zqfzyqtx.html