Object.assign does not copy correctly

后端 未结 3 584
执念已碎
执念已碎 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:51

    You don't have to use a library, unless you really need a deep copy (I did not need one). Just do this:

    this.editItem = {...item};
    

    The ... operator will decompose item into its keys and values, and since you're doing that in an object literal (the { }), it uses those as the keys and values of the new object.

    Might be helpful to other people who, like me, don't need a deep copy. Object.assign just straight-up doesn't work, and this does.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-31 19:01

    If the methods you used isn't working well with objects involving data types, try this

    import * as _ from 'lodash';
    

    Deep clone object

    myObjCopy = _.cloneDeep(myObj);
    
    0 讨论(0)
提交回复
热议问题