0

Why is my Employee object being changed when I've replicated it and I'm making changes to my new variable?

const Employee = { firstname: 'John', lastname: 'Doe' }

const EmployeeModifier = Employee;

console.log(EmployeeModifier.firstname);
delete EmployeeModifier.firstname;
console.log(Employee.firstname);

Right now this returns

> "John"
> undefined

Ideally it would return

> "John"
> "John"

But something is causing the delete command to remove from BOTH Employee and EmployeeModifier. Why? And how can I change this?

O P
  • 2,327
  • 10
  • 40
  • 73
  • 4
    `const x = y` doesn't copy an object. It just copies the _reference_ to the object. So that's why modifications are being observed on both variables. – JLRishe Jan 07 '20 at 16:31
  • `EmployeeModifier` and `Employee` both have same reference in the memory means that both are same object with different names. You need close an object instead of assigning `const EmployeeModifier ={...Employee}`. – Maheer Ali Jan 07 '20 at 16:32

1 Answers1

0

Because it's a reference to the original object. You will need to do a shallow/deep copy.

This is probably sufficient for you:

const oldObject = {
  firstname: 'John',
  address: {
    street: '123 Street',
    city: 'Fake Town'
  }
}

const newObject = JSON.parse(JSON.stringify(oldObject));

This method has it's own problems, though. You can also use lodash's cloneDeep which is going to cover more cases.

Read here for more information on shallow/deep copying.

Ian
  • 544
  • 3
  • 16