JSON stringify ES6 class property with getter/setter

You can use toJSON method to customise the way your class serialises to JSON:

class MyClass {
  constructor(property) {
    this.property = property
  }

  set property(prop) {
  // Some validation etc.
  this._property = prop
  }

  get property() {
    return this._property
  }

  toJSON() {
    return {
      property: this.property
    }
  }
}

Leave a Comment