1

I have a Wallet class, and wallet is an instance of this class. I had to JSON.stringify(wallet) it save in a file. Now, when I do JSON.parse(JSON.stringify(wallet)) then it is no more an instanceof Wallet.

How to convert this plain object from JSON.parse to intanceof Wallet ?

Masoom Raj
  • 71
  • 5
  • 3
    Does this answer your question? [Parse JSON String into a Particular Object Prototype in JavaScript](https://stackoverflow.com/questions/5873624/parse-json-string-into-a-particular-object-prototype-in-javascript) – jonrsharpe Aug 07 '20 at 15:36

2 Answers2

1

You could use Object.assign(target, source) to assign the properties of the plain object to your instance.

Please do care to read all the gotcha's mentioned in the MDN docs linked, especially if you have nested objects.

let plain = { 
   foo : 'bar',
   count : 42
}
class Complex {
    constructor() {
        this.foo = 'hello';
        this.count = 10; 
    }
    
    getCount() {
        return this.count;
    }
    
    getFoo() {
        return this.foo;
    }
}
let test = new Complex();
console.log(test.getFoo());
console.log(test.getCount());
console.log('==== assigning plain object ===');

Object.assign(test, plain);

console.log(test.getFoo());
console.log(test.getCount());
Tschallacka
  • 27,901
  • 14
  • 88
  • 133
1

Just use Object.assign(), like so:

const walletLiteral = JSON.parse(response);
const walletInstance = Object.assign(new Wallet(), walletLiteral);
JayCodist
  • 2,424
  • 2
  • 12
  • 28