在调用 JSON.stringify() 的时候可以使用第二个参数 replacer。这个参数接收 function/array,用来起到选择和筛选属性的作用。如果这个参数给出的是 null ,那么所有属性都会被返回。若参数是函数,则函数的参数分别是 key 和 value。

    1. // function
    2. function replacer(key, value) {
    3. // Filtering out properties
    4. if (typeof value === 'string') {
    5. return undefined;
    6. }
    7. return value;
    8. }
    9. var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
    10. JSON.stringify(foo, replacer); // '{"week":45,"month":7}'
    11. // array
    12. JSON.stringify(foo, ['week', 'month']);
    13. // '{"week":45,"month":7}', only keep "week" and "month" properties

    当遇到对象循环引用的时候,这时候使用 JSON.stringify() 会报错。

    1. const obj = { a: 123 }
    2. obj.myself = obj

    image.png
    为解决报错的问题,我们可以使用 replacer 参数来进行过滤。

    1. const getCircularReplacer = () => {
    2. const seen = new WeakSet();
    3. return (key, value) => {
    4. if (typeof value === "object" && value !== null) {
    5. if (seen.has(value)) {
    6. return;
    7. }
    8. seen.add(value);
    9. }
    10. return value;
    11. };
    12. };
    13. JSON.stringify(obj, getCircularReplacer()); // '{"a":123}'