JSON stringify ES6 class property with getter/setter

后端 未结 5 1798
一向
一向 2020-11-30 13:40

I have a JavaScript ES6 class that has a property set with set and accessed with get functions. It is also a constructor parameter so the class can

5条回答
  •  既然无缘
    2020-11-30 14:04

    As mentioned by @Amadan you can write your own toJSON method.

    Further more, in order to avoid re-updating your method every time you add a property to your class you can use a more generic toJSON implementation.

    class MyClass {
    
      get prop1() {
        return 'hello';
      }
      
      get prop2() {
        return 'world';
      }
    
      toJSON() {
    
        // start with an empty object (see other alternatives below) 
        const jsonObj = {};
    
        // add all properties
        const proto = Object.getPrototypeOf(this);
        for (const key of Object.getOwnPropertyNames(proto)) {      
          const desc = Object.getOwnPropertyDescriptor(proto, key);
          const hasGetter = desc && typeof desc.get === 'function';
          if (hasGetter) {
            jsonObj[key] = desc.get();
          }
        }
    
        return jsonObj;
      }
    }
    
    const instance = new MyClass();
    const json = JSON.stringify(instance);
    console.log(json); // outputs: {"prop1":"hello","prop2":"world"}

    If you want to emit all properties and all fields you can replace const jsonObj = {}; with

    const jsonObj = Object.assign({}, this);
    

    Alternatively, if you want to emit all properties and some specific fields you can replace it with

    const jsonObj = {
        myField: myOtherField
    };
    

提交回复
热议问题