How to convert a TypeScript object to a simple object?

I use the JS library, especially select2 , which acts a little differently than I would like if the objects I pass are not simple objects. All this is checked using the jQuery isPlainObject function.

Does TypeScript have a listing that I don’t know about to achieve this without resorting to writing my own?

 class Opt { constructor(public id, public text) { } toPlainObj(): Object { return { id: this.id, text: this.text } } } let opts = [ new Opt(0, 'foo'), new Opt(1, 'bar') ]; console.clear() console.log('both should be false') $.map(opts, opt => { console.log($.isPlainObject(opt)) }) console.log('both should be true') $.map(opts, opt => { console.log($.isPlainObject(opt.toPlainObj())) }) 
+8
source share
2 answers

You can use Object.assign () :

 class Point { private x: number; private y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } getX(): number { return this.x; } getY(): number { return this.y; } } let p1 = new Point(4, 5); let p2 = Object.assign({}, p1); 

p1 is an instance of the class, and p2 is just { x: 4, y: 5 } .

And using the toPlainObj method:

 class Point { private x: number; private y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } getX(): number { return this.x; } getY(): number { return this.y; } toPlainObj(): { x: number, y: number } { return Object.assign({}, this); } } 

If this is what you need in more classes, you can have a base class that has this method:

 class BaseClass<T> { toPlainObj(): T { return Object.assign({}, this); } } class Point extends BaseClass<{ x: number, y: number }> { private x: number; private y: number; constructor(x: number, y: number) { super(); this.x = x; this.y = y; } getX(): number { return this.x; } getY(): number { return this.y; } } 
+11
source

Something like this works:

 let plainObj; try { plainObj = JSON.parse(JSON.stringify(obj)); } catch(e) { console.error(e) } 
0
source

All Articles