javascript - How to create mutable AND immutable copy of object in JS - Stack Overflow

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

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?

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?

Share Improve this question asked May 4, 2016 at 23:05 HimmelHimmel 3,7097 gold badges43 silver badges78 bronze badges 2
  • Is this a deeply nested object, or is it only one level deep regarding the properties? – Montagist Commented May 4, 2016 at 23:08
  • nested 2 levels deep, but I only want to mutate properties in the first level – Himmel Commented May 4, 2016 at 23:11
Add a ment  | 

2 Answers 2

Reset to default 4
var objCopy = {};

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

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

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

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744110144a4558913.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信