Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.assign does not copy correctly

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]:

enter image description here

But when I edit the clone Object this.itemEditado:

enter image description here

the original Object this.roteiroCompleto[0] changes too.

enter image description here

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:

enter image description here

The strange thing is, in another Vue Component, I use the same strategy, and it works.

like image 817
extraxt Avatar asked May 25 '18 02:05

extraxt


2 Answers

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.

like image 180
Garrett Johnson Avatar answered Nov 15 '22 19:11

Garrett Johnson


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);
like image 38
Metin Atalay Avatar answered Nov 15 '22 18:11

Metin Atalay