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

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

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 Denunciar

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