Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

232
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda