0

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 ?

SamS87
  • 41
  • 1
  • 6

2 Answers2

0

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

const originalData = JSON.parse(JSON.stringify(docid[0][0].Record));
Zeeshan Anjum
  • 944
  • 8
  • 16
  • Is that the only way to deep clone by stringify and parse, wondering how efficient it is. – SamS87 Sep 17 '21 at 22:01
  • its most efficient. see example [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#warning_for_deep_clone) – Zeeshan Anjum Sep 17 '21 at 22:03
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);
SamS87
  • 41
  • 1
  • 6