The docs for Object.freeze()
state that it only allows freezing the object if its primitive type is actually "object". I'm working with some JSON data objects and was hoping to use this to set specific properties to be immutable (e.g. uuid, which is immutable in the db). Object.freeze()
seemed like the perfect solution, until:
TypeError: Object.freeze called on non-object
Darn.
So, assuming I've got an object (parsed from JSON) like this:
{
"uuid": "765926c1-911e-49b2-b597-48cf0df59a17",
"firstName": "Bob",
"lastName": "Dole"
}
is there any way I can force uuid to be immutable?
Unlike Object. seal() , existing properties in objects frozen with Object. freeze() are made immutable and data properties cannot be re-assigned.
We can freeze an object to make it immutable. You use the method Object. freeze to freeze an object. You can not create a new property, modify or delete an existing property, or extend the object when a freeze is applied.
Object.freeze() Method freeze() which is used to freeze an object. Freezing an object does not allow new properties to be added to an object and prevents from removing or altering the existing properties. Object. freeze() preserves the enumerability, configurability, writability and the prototype of the object.
Object. freeze() makes an object immune to everything even little changes cannot be made. Object. seal() prevents from deletion of existing properties but cannot prevent them from external changes.
Yes, you need to use Object.defineProperty
and re-define uuid
property descriptor to be non-writable and non-configurable:
Object.defineProperty(obj, "uuid", { configurable: false, writable: false });
configurable: false
means that from now uuid
property descriptor can't be defined again. That is, no other sentence will be able to let the property be mutable again.
At the end of the day, Object.freeze
is like a shortcut which iterates all enumerable properties in a given object and turns them into non-configurable+non-writable ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With