Object.assign does not copy correctly

后端 未结 3 583
执念已碎
执念已碎 2020-12-31 18:24

I\'m working with VueJS.

I have a Method that receives a Object as argument.

Then I clone this Object with Object.assign().

Comp         


        
3条回答
  •  粉色の甜心
    2020-12-31 18:55

    Object.assign only does a shallow copy of the keys and values, meaning if one of the values in the object is another object or an array, then it is the same reference as was on the original object.

    var x = { a: 10, b: { c: 100 } };
    var y = Object.assign({}, x);
    
    y.a = 20;
    console.log( x.a, y.a ); // prints 10 20
    
    y.b.c = 200;
    console.log( x.b.c, y.b.c ) // prints 200 200
    

    To deep copy an object, you can using something like the cloneDeep function in lodash or take an uglier approach using built in functions with JSON.parse( JSON.stringify( obj ) ).

    Note that the second option will only work with primitive types that are supported by JSON.

提交回复
热议问题