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?

5
  • 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 Commented May 16, 2016 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. Commented May 16, 2016 at 13:07
  • well not all of them are referenced, id/name arent Commented May 16, 2016 at 13:11
  • Thanks, for clarifying @Pointy. Now I get it Commented May 16, 2016 at 13:35
  • Possible duplicate of JS: Does Object.assign() create deep copy or shallow copy Commented May 17, 2016 at 4:48

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.