Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

233
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda