Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
Javascript delete property in object and retain original object data

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
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!