最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin10浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论