Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to freeze nested objects in javascript?

Tags:

javascript

I just stumbled upon Object.freeze() function. It seems to be a pretty good feature but how to make whole object (including nested objects) immutable?

For example I can change innerProp here:

const obj = { prop: { innerProp: 1 } };
obj.prop.innerProp = 5;
console.log(obj.prop.innerProp); // 5

Is it possible do freeze nested objects too? (ECMAScript 5/6)

like image 669
madox2 Avatar asked Jan 13 '16 20:01

madox2


1 Answers

function deepFreeze (o) {
  Object.freeze(o);
  if (o === undefined) {
    return o;
  }

  Object.getOwnPropertyNames(o).forEach(function (prop) {
    if (o[prop] !== null
    && (typeof o[prop] === "object" || typeof o[prop] === "function")
    && !Object.isFrozen(o[prop])) {
      deepFreeze(o[prop]);
    }
  });

  return o;
};

https://github.com/substack/deep-freeze

It's public domain so you don't have to give credit :D

like image 175
birdoftheday Avatar answered Oct 04 '22 16:10

birdoftheday