I'm working with VueJS.
I have a Method that receives a Object as argument.
Then I clone this Object with Object.assign()
.
Component.vue
export default {
// ...
methods: {
// ...
activateEditMode (item) {
this.editItemIndex = this.travelItinerary.indexOf(item)
this.editItem = Object.assign({}, item)
// ...
}
}
}
The original Object at this.roteiroCompleto[0]
:
But when I edit the clone Object this.itemEditado
:
the original Object this.roteiroCompleto[0]
changes too.
I tried to copy each key and value, copy only the Array with .slice()
, .map(a=>a)
, and nothing works. The two objects keep binding.
When I console.log(this.itemEditado)
, I get this:
The strange thing is, in another Vue Component, I use the same strategy, and it works.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With