Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutates a cloned object, mutates the original object too [Javascript]

I'm writing some test for React Components with Jest in ES6. In one test, i need clone a json imported and mutate the cloned object, but when i mutate the object cloned, the original object mutates too!

import obj from './object.json';    // obj = { name: 'someName' }


describe('Testing a component', () => {

  it('Some testing', () => {
    const obj2 = Object.assign({}, obj);  //Clone the object
    obj2.name = 'otherName';  // Muatate the object

    console.log(obj); // { name: 'otherName' }
  });

})

Why this happen? Why when i mutate the cloned object, the original imported object mutates too?

like image 679
Guillermo Puente Sandoval Avatar asked Oct 18 '25 15:10

Guillermo Puente Sandoval


1 Answers

Object.assign only does a shallow clone. That means the internal objects are still pointing to the original ones.

To do a deep clone you can use Lodash or immutability-helper.

like image 98
Kraylog Avatar answered Oct 21 '25 06:10

Kraylog