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

So, I have a Javascript module that looks like this:

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 calling it explicitly Object.freeze()for each object? I understand that I can just skip the array and freeze each one before exporting, but I was curious to find out if there was a more elegant solution.

+4
source share
4 answers

All you have to do is pass Object.freezein 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
Run code
+5
source

, . deep freeze https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

, :

obj1 = {
  internal: {}
};

Object.freeze(obj1);
obj1.internal.a = 'aValue';

obj1.internal.a // 'aValue'

// To make obj fully immutable, freeze each object in obj.
// To do so, we use this function.
function deepFreeze(obj) {

  // Retrieve the property names defined on obj
  var propNames = Object.getOwnPropertyNames(obj);

  // Freeze properties before freezing self
  propNames.forEach(function(name) {
    var prop = obj[name];

    // Freeze prop if it is an object
    if (typeof prop == 'object' && prop !== null)
      deepFreeze(prop);
  });

  // Freeze self (no-op if already frozen)
  return Object.freeze(obj);
}

obj2 = {
  internal: {}
};

deepFreeze(obj2);
obj2.internal.a = 'anotherValue';
obj2.internal.a; // undefined
0

data.forEach(Object.freeze) is the best you can do.

In your case, you can clear your code like this:

const data = [
  unmodifiableObj(0, 'Foo'),
  unmodifiableObj(1, 'Bar')
]

export default data;


function unmodifiableObj(id, name) {
  return Object.freeze({ id, name })
}
-1
source

Updated with sample code from MDN

Try the following:

// To make obj fully immutable, freeze each object in obj.
// To do so, we use this function.
function deepFreeze(obj) {

// Retrieve the property names defined on obj
var propNames = Object.getOwnPropertyNames(obj);

// Freeze properties before freezing self
propNames.forEach(function(name) {
var prop = obj[name];

// Freeze prop if it is an object
if (typeof prop == 'object' && prop !== null)
  deepFreeze(prop);
});

// Freeze self (no-op if already frozen)
return Object.freeze(obj);
}

which freezes the array itself, as well as any of its objects.

-1
source

Source: https://habr.com/ru/post/1651718/


All Articles