改变克隆对象,也改变原始对象 [Javascript]

Gui*_*val 3 javascript testing object mutation jestjs

我正在 ES6 中使用 Jest 为 React 组件编写一些测试。在一个测试中,我需要克隆导入的 json 并变异克隆的对象,但是当我变异克隆的对象时,原始对象也会变异!

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' }
  });

})
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况?为什么当我改变克隆的对象时,原始导入的对象也会改变?

Kra*_*log 5

Object.assign只进行浅克隆。这意味着内部对象仍然指向原始对象。

要进行深度克隆,您可以使用Lodashimmutability-helper