Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good way to freeze an array of objects in Javascript?

Tags:

javascript

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.

like image 966
kibowki Avatar asked Aug 18 '16 21:08

kibowki


People also ask

Can I freeze an array in JavaScript?

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.

How do you seal an array in JavaScript?

seal() is used for sealing objects and arrays. Object. seal() is used to make an object immutable.

Is object freeze good?

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.

How do you freeze an object in JavaScript?

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.


1 Answers

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
like image 63
Mike Cluck Avatar answered Sep 18 '22 11:09

Mike Cluck