I have an instance of a class, say
class MyObject{
id: number = 0;
data: string = "";
constructor(){
}
toString(){
return `${this.id}: ${this.data}`;
}
}
const myObj = new MyObject()
myObj.data = "hello"
How to convert it to a plain JS object:
const output = {id: 10, data: "hello"}
I know this works, but there must be a way without serializing the whole object:
const output = JSON.parse(JSON.stringify(myObj))
What is the best way to do this?
Note that I’m looking for a generic solution, not like this:
toObject() {
return {
id: this.id,
data: this.data,
};
}
2
Answers
To create an object with just the properties and not the methods of an instance, you can use
Object.assign()
to copy all the object’s enumerable own properties to another object, which can specify as a new, plain, object.For simple cases you can use the object literal spread syntax:
If your original object has nested custom objects — that also need to convert to plain objects or arrays — then either make a recursive function, or use the
structuredClone
function (added in ECMAScript 2023, Node 17). Here is a more realistic example with a linked list implementation:Note however that this does serialise/deserialise the whole object behind the scenes, and where native classes are involved, they are also maintained in the target object (like
Set
,Map
,Date
,RegExp
,Number
, …). This may or may not be what you want, but realise thatJSON.stringify
on such instances also has particular results: for aSet
,Map
orRegExp
you get an empty object, for aDate
you get a string, …etc, so this may need special care — depending on expectations.