Himmel Himmel - 1 year ago 52
Javascript Question

How to create mutable AND immutable copy of object in JS

Without using any additional libraries, how I can I create an immutable copy of an object and retain a mutable copy.

var mutableCopy = immutableData;


mutableCopy.newProp = 'mutated!';

console.log(mutableCopy.hasOwnProperty('newProp')); // false

It seems that
also freezes objects by reference.

How can I create a mutable and immutable copy of an object?

Answer Source
var objCopy = {};

for ( var propKey in objToClone )
    objCopy[ propKey ] = objToClone[ propKey ];

And object.freeze whichever you prefer. If you've a more complex/deeper object and need to mutate those deeper properties, I'd probably just use something hacky like

var objCopy = JSON.parse( JSON.stringify( objToClone ) );