0

I'm trying to delete a known key from a Javascript object. I've created a tiny reproduction here, and the result is the same when compared to a much larger object. I'm assigning an object to a new variable, and want to delete the key from the new variable without changing the original variable, but that's not working.

The original key is also getting deleted which isn't correct, what do I need to change to prevent this?

const person = {
  name: 'john',
  age: 50
}

const newPerson = person
delete newPerson.name

console.log(person) <-- contains only name, I expect name and age since I'm only deleting from newly created newPerson variable
Ryan H
  • 2,620
  • 4
  • 37
  • 109
  • when you do `const newPerson = person`, you only assign reference of object to `newPerson` so when you delete it, you delete ir from both, if you want to 'separate' object, you need to do this : `const newPerson = Object.assign({}, person);` – ekans Sep 16 '21 at 09:45

1 Answers1

1

In your example you are assigning const newPerson = person;

What this will do?

This will create a new variable with name newPerson pointing to the memory location of variable person. This is called Shallow Copy.

If you dont want to share the memory address, instead an independent variable with different memory address, you have to perform Deep Copy.

You can perform this with n number of ways. Spread operator is one helpful tool for performing Deep Copy for objects.

Not just Spread Operator, Object.assign({}, data), JSON.parse(JSON.stringigy(data)) will also perform the same action.

Deep Copy v/s Shallow Copy

In programming, we store values in variables. Making a copy means that you initiate a new variable with the same value(s). However, there is a big potential pitfall to consider: deep copying vs. shallow copying. A deep copy means that all of the values of the new variable are copied and disconnected from the original variable. A shallow copy means that certain (sub-)values are still connected to the original variable.

Reference 1 Reference 2

const person = {
  name: 'john',
  age: 50
}

const newPerson = { ...person };
delete newPerson.name;

console.log(person);
Nitheesh
  • 19,238
  • 3
  • 22
  • 49