2

Today, I was working with redux.

When I was creating a copy with Object.assign with objects without inner arrays, it worked well.

But when I had to deal with an object like this:

{
      ID:'2',
      NAME:'GENERAL',
      FIELDS:[
        {
          ID:'1',
          NAME:'M2'
        }
      ]
    }

, Object assign would make a copy, but the changes that I made in the copy were happening in the original too.

I have to use lodash cloneDeep.

Anyone knows why this behaviour happens?

kloddant
  • 1,026
  • 12
  • 19
  • Becuase Object.assign, doesnt clone or deep copy, it simply copy reference of the other object's properties. so when you have primitives like string or numbers they are copied by arrays or objects are transferred by reference – Neta Meta May 16 '16 at 13:07
  • 1
    Object values are references in JavaScript. That "FIELDS" property, for example, has as its value a reference to an array. When you copy the properties of that object to another object, the "FIELDS" property value - the reference - is copied, so now the properties of both objects refer to the same array. That's why `cloneDeep` exists. In my experience, deep object copies are very rarely needed. – Pointy May 16 '16 at 13:07
  • well not all of them are referenced, id/name arent – Neta Meta May 16 '16 at 13:11
  • Thanks, for clarifying @Pointy. Now I get it – Gabriel García Seco May 16 '16 at 13:35
  • Possible duplicate of [JS: Does Object.assign() create deep copy or shallow copy](http://stackoverflow.com/questions/34504682/js-does-object-assign-create-deep-copy-or-shallow-copy) – Sheepy May 17 '16 at 04:48

0 Answers0