How can an object created with a null prototype using Object.create(null,{...})
be stored in a database and restored?
And, if all you are given is the stringified object, can it be parsed to a desired prototype?
JSON.parse()
returns an object with the default prototype.
For example,
let nullObj = Object.create(null, {
a: {
value: 10,
writable: true
},
b: {
value: 'Text'
}
});
let jsonObj = JSON.parse('{"a":10,"b":"Text"}');
2
Answers
You can use
Object.assign()
with the base object created byObject.create(null)
and the object parsed from the JSON string.You can also set the prototype of the parsed object using
Object.setPrototypeOf()
.Here’s a demonstration of both approaches:
to be able to store and restore an object created by
Object.create(null,{...})
you would have to use[JSON.stringify()]
the code would look like this