Answer the question
In order to leave comments, you need to log in
How to preserve the type of an object in JavaScript after JSON conversions?
Sorry for the noob question, I'm just starting to learn JS.
I have the following constructor
function User(id, name) {
this.id = id;
this.name = name;
}
var user = new User(1, 'Вася');
var json = JSON.stringify(user);
var user2 = JSON.parse(json);
console.log(user2 instanseof User); // false
Answer the question
In order to leave comments, you need to log in
There is no such mechanism. You can use something like this (working example https://jsfiddle.net/83bun7xt/ ):
function serialize(entity) {
return JSON.stringify({ type: entity.constructor.name, data: entity });
}
function deserialize(str, types) {
var parsed = JSON.parse(str);
return types[parsed.type] ? new types[parsed.type](parsed.data) : {};
}
function User(data) {
this.id = data.id;
this.name = data.name;
}
var user = new User({ id: 1, name: 'Nik' });
console.log('User ->', user, ' instanceOf User ===', user instanceof User);
// User -> User {id: 1, name: "Nik"} instanceOf User === true
var userJSON = serialize(user);
console.log('Serialized user ->', userJSON);
// Serialized user -> {"type":"User","data":{"id":1,"name":"Nik"}}
var restoredUser = deserialize(userJSON, { 'User': User });
console.log('Deserialized user ->', restoredUser, ' instanceOf User ===', restoredUser instanceof User);
// Deserialized user -> User {id: 1, name: "Nik"} instanceOf User === true
//
There is no such mechanism, because objects are compared, but they are different! But you can compare, not by reference, but by content, i.e. compare json strings or run through the fields comparing their values.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question