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 be instantiated with said property.
class MyClass {
constructor(property) {
this.property = property
}
set property(prop) {
// Some validation etc.
this._property = prop
}
get property() {
return this._property
}
}
I use _property
to escape the JS gotcha of using get/set that results in an infinite loop if I set directly to property
.
Now I need to stringify an instance of MyClass to send it with a HTTP request. The stringified JSON is an object like:
{
//...
_property:
}
I need the resulting JSON string to preserve property
so the service I am sending it to can parse it correctly. I also need property
to remain in the constructor because I need to construct instances of MyClass from JSON sent by the service (which is sending objects with property
not _property
).
How do I get around this? Should I just intercept the MyClass instance before sending it to the HTTP request and mutate _property
to property
using regex? This seems ugly, but I will be able to keep my current code.
Alternatively I can intercept the JSON being sent to the client from the service and instantiate MyClass with a totally different property name. However this means a different representation of the class either side of the service.
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.If you want to emit all properties and all fields you can replace
const jsonObj = {};
withAlternatively, if you want to emit all properties and some specific fields you can replace it with
I made some adjustments to the script of Alon Bar. Below is a version of the script that works perfectly for me.
You can use
toJSON
method to customise the way your class serialises to JSON:If you want to avoid calling toJson, there is another solution using enumerable and writable: