So I have a Javascript module that looks like the following:
const data = [
{
id: 'do not modify',
name: 'do not modify'
},
{
id: 'do not modify 2',
name: 'do not modify 2'
}
];
export default data;
Is there a clean way I can recursively freeze all objects in an array without explicitly calling Object.freeze()
on each and every object? I realize I could just loop through the array and freeze each of them before exporting, but I was curious to know if there was a more elegant solution.
As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. freeze() returns the same object that was passed into the function.
seal() is used for sealing objects and arrays. Object. seal() is used to make an object immutable.
The only practical use for Object. freeze is during development. For production code, there is absolutely no benefit for freezing/sealing objects. In strict mode, this would throw an error if myObject was frozen.
You can freeze (make immutable) an object using the function Object. freeze(obj) . The object passed to the freeze method will become immutable. The freeze() method also returns the same object.
All you'd have to do is pass Object.freeze
to Array.prototype.forEach
:
'use strict';
var objs = [
{ a: 1 },
{ b: 2 },
{ c: 3 }
];
objs.forEach(Object.freeze);
objs[0].a = 4; // Fails due to being frozen
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