Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.freeze to freeze a property? Or how to set a property to be immutable/read-only?

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?

like image 304
brandonscript Avatar asked Sep 13 '15 07:09

brandonscript


People also ask

Is object freeze immutable?

Unlike Object. seal() , existing properties in objects frozen with Object. freeze() are made immutable and data properties cannot be re-assigned.

How do you make an object property immutable?

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.

How do you freeze a property in an object?

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.

What's the difference between object seal and object freeze methods?

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.


1 Answers

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.

like image 188
Matías Fidemraizer Avatar answered Oct 13 '22 00:10

Matías Fidemraizer