Hide certain values in output from JSON.stringify()

后端 未结 13 1580
有刺的猬
有刺的猬 2020-12-02 15:13

Is it possible to exclude certain fields from being included in the json string?

Here is some pseudo code

var x = {
    x:0,
    y:0,
    divID:\"xyz         


        
13条回答
  •  日久生厌
    2020-12-02 15:53

    Note for Miroslaw Dylag's answer: The defined property should be its own property. Otherwise it would fail.

    Doesn't work:

    class Foo {
    }
    Object.defineProperty(Foo.prototype, 'bar', { value: 'bar', writable: true });
    
    const foo = new Foo();
    foo.bar = 'baz';
    alert(JSON.stringify(foo).indexOf('bar') === -1); // false (found)
    

    Works:

    class Foo {
      constructor() {
        Object.defineProperty(this, 'bar', { value: 'bar', writable: true });
      }
    }
    
    const foo = new Foo();
    foo.bar = 'baz';
    alert(JSON.stringify(foo).indexOf('bar') === -1); // true (not found)
    

提交回复
热议问题