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

129
Visualizações
Copying objects in js (need guidance on pass by reference from docs)

I looked in the js docs and while studying the doc it mentioned in object.assign() If the source value is a reference to an object, it only copies the reference value.

In my below snippet, one alters the original object and the other doesn't

    var objA = {
    a: 1,
    b: {
       c: 2,
       d: {
       e: 3,
     },
    },
  } 
var objC = { t: 1 };

  //why this works i.e adds a to objEmpty
// var objEmpty = Object.assign({}, { objC });  //this would add a prop to the objEmpty object

//this doesnt work i.e doesnt add a to objEmpty
var objEmpty = Object.assign({}, objC);  //this will not
objC.a = 3;

console.log(objC);

console.log(objEmpty);

I am getting my head around how really things work by trying different scenarios and I believe that it is something related to reference but how?

Another example from the docs

  const obj2 = Object.assign({}, obj1);
  console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}

  obj1.a = 1;
  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
  console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}

  obj2.a = 2;
  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
  console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 0}}
  obj2.b.c = 3;
  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 3}}
  console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 3}}```

why does js behave this way? why the 3 got changed but the other didn't?

Thanks in advance :)
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

why does js behave this way? why the 3 got changed but the other didn't?

Because Object.assign() actually does Shallow Copy, you need to do Deep Copy

To do deep copy of an object.

There are bunch of ways, The most common and popular way is to use JSON.stringify() with JSON.parse().

const oldObj = {a: {b: 1}, c: 2};
const newObj = JSON.parse(JSON.stringify(oldObj));
oldObj.a.b = 3; // will not affect the newObj
console.log('oldObj', oldObj);
console.log('newObj', newObj);

Note: There's a new JS standard called structured cloning. It works on all browsers:

method creates a deep clone of a given value using the structured clone algorithm.

const clone = structuredClone(object);
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