3

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

var mutableCopy = immutableData;

Object.freeze(immutableData);

mutableCopy.newProp = 'mutated!';

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

It seems that Object.freeze() also freezes objects by reference.

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

2
  • Is this a deeply nested object, or is it only one level deep regarding the properties? Commented May 4, 2016 at 23:08
  • nested 2 levels deep, but I only want to mutate properties in the first level Commented May 4, 2016 at 23:11

2 Answers 2

4
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 ) );
Sign up to request clarification or add additional context in comments.

2 Comments

JSON.deserialize/serialize? Do you mean JSON.parse/stringify?
I tried var objCopy = Object.create(objToClone); which I found on another SO question which didn't work for copying the package.json file by reference, but the JSON stringify and then parse worked. Thanks!
1

You are slightly right in this is a problem of pass-by-reference vs pass-by-value. In reality, the pass-by-reference occurs in the first line. Both mutableCopy and immutableData point to the same object on the JS heap.

What you should do is make a new object that is a duplicate of the old one. Then, freezing the new object will leave the old one as a mutable copy while preventing modifications.

var newObj = {}
for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        newObj[key] = obj[key];
    }
}

Object.freeze(newObj);

You can, of course, make the new object the mutable copy and the old one the immutable one should you so choose.

3 Comments

Even without the Object.freeze I could modify the properties of newObj here, and the properties of obj still wouldn't change, right?
Looks like I wouldn't need to use Object.freeze
You are correct. If you modify either obj or newObj after copying, the other will not change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.