Himmel Himmel - 2 years ago 93
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 ) );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download