Q:

Is there a good way to freeze an array of objects in 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.

A:

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

