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

107
Visualizações
Coyping by reference issue in NodeJS

Ok i thought i had it figured out but i guess i was wrong. I previously posted the issue where because javascript an object is copied as a reference of the original, changes to the original object will also be reflected in the copy. So based on the recommendations of using

const originalData = {...docid[0][0].Record}
// or
const originalData = Object.assign({}, docid[0][0].Record)

i revised my code to use them with not much luck. My code looks now like this..

 // Assign the Data from query
 // const originalData = {...docid[0][0].Record}
 const originalData = Object.assign({}, docid[0][0].Record)
 // Delete the History & DocId Object from Data Object
 delete originalData['History']
 delete originalData['DocId']

and if i print to console.log(originalData) the data is correct. Now in my code i update some data and have a function that compares the data to create a diff file so that's why i need the originalData.

After i run this below code which takes my new data and map's it , removes the undefined etc

 // Mailing Address
 let MailingAddrObj = update.mailingAddress
 Object.keys(MailingAddrObj).forEach(key => MailingAddrObj[key] === undefined && delete MailingAddrObj[key])
 let MailingAddress = _.extend(docid[0][0].Record.mailingAddress, MailingAddrObj)

but for some reason the last command also modify's my originalData which i thought was either deep copy and that should not happen. So if i print the originalData after this code it reflects the new data in the MailingAddress object.

So what am i missing here or what's wrong ?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Object.assign will not work for deep clone. use like this

const originalData = JSON.parse(JSON.stringify(docid[0][0].Record));
about 4 years ago · Juan Pablo Isaza Relatório

0

After a bit more searching, i found a solution based on lodash which looks cleaner to me specially as i use already lodash in my code.

const _ = require('lodash');
var obj = [{  x: 1 }, {y: 2}];
  // Deep copy
var deepCopy = _.cloneDeep(obj);
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