Sometimes, we want to stringify an ES6class property with getter or setter into JSON.
In this article, we’ll look at how to stringify an ES6class property with getter or setter into JSON.
Stringify an ES6 Class Property with Getter or Setter into JSON
To stringify an ES6class property with getter or setter into JSON, we can add the toJSON
method to the class to customize what to put in the JSON string.
For instance, we can write:
class MyClass {
constructor(property) {
this.property = property
}
set property(prop) {
this._property = prop
}
get property() {
return this._property
}
toJSON() {
return {
property: this.property
}
}
}
console.log(JSON.stringify(new MyClass('foo')))
to add the property
property into the MyClass
class.
We have the this.property
instance property which is formed with getters and setters.
We just return an object with this.property
set to the property
property in toJSON
to include.
Then when we create a new MyClass
instance, we should see the this.property
logged when we cal JSON.stringify
on the MyClass
instance.
Conclusion
To stringify an ES6class property with getter or setter into JSON, we can add the toJSON
method to the class to customize what to put in the JSON string.
2 replies on “How to Stringify an ES6 Class Property with Getter or Setter into JSON?”
Unfortunately this will omit all other properties.. is there a way to include everything and just add the property you want?
You can add as many properties into the object returned in toJSON as you want.