0

and I trying to clone an object with Object assing.

const defaults = {
   a: [],
   b: [],
   c: [],
   d: [],
   e: [],
   f: [],
   g: []
};

this.rowSetSlug = Object.assign({},defaults);
this.rowSetObject = Object.assign({},defaults);
this.rowSetModified = Object.assign({},defaults);

But when I fill one object like

this.rowSetObject.push(object);

And do a console.log()

console.log(this.rowSetObject);
console.log(this.rowSetModified);
console.log(this.rowSetSlug);

All same have the rowSetObject items, and if i fill another they replicate.

Thanks

rzx10r
  • 134
  • 1
  • 1
  • 9
  • This is due to the fact that you are cloning first level attributes, but when array values comes, them get _referenced_ beacause of object type. You have to deep clone your object, cloning every single array and paying attention that each element is not a reference object itself: only primitives are cloned by value: https://medium.freecodecamp.org/understanding-by-reference-vs-by-value-d49139beb1c4 – Mosè Raguzzini Mar 16 '19 at 08:48
  • First thanks for the awnser, has some function to do a deep clone? for each element on the array, or has to do a foreach ?! – rzx10r Mar 16 '19 at 12:38
  • There are a lot of libraries that provide deep clone, try _.deepClone() of lodash library (https://lodash.com/) – Mosè Raguzzini Mar 18 '19 at 08:15

0 Answers0