Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash equivalent of JSON.parse(JSON.stringify())

I am currently cloning an object with:

var copy = JSON.parse(JSON.stringify(original));

When I try lodash - it seems the recommended way is cloneDeep() but that makes a total mess for me. My object is partially made up of the result of a Mongoose query which may be what is causing this.

Original:

template: 'email/receipt.swig',
templateVars: { 
  code: '299137819',

Cloneed with lodash:

template: 'email/receipt.swig',
templateVars: { 
  '$__': { 
    strictMode: true,
    selected: undefined,
    shardval: undefined,
    saveError: undefined,
    validationError: undefined,
    adhocPaths: undefined,
    removing: undefined,
    inserting: true,
    version: undefined,
    getters: [Object],
    _id: undefined,
    populate: undefined,
    populated: [Object],
    wasPopulated: false,
    scope: [Circular],
    activePaths: [Object],
    ownerDocument: undefined,
    fullPath: undefined 
  },
  isNew: false,
  errors: undefined,
  _maxListeners: 0,
  _events: { save: [Object], isNew: [Object] },
  _doc: { 
    code: '299137819'

What is happening here? This is clearly Mongo stuff but why the reformat? Is there no way to make an exact copy with lodash? Not that my current method is a pain - just trying to understand why people say cloneDeep is the equivalent.

like image 838
cyberwombat Avatar asked Oct 31 '22 18:10

cyberwombat


1 Answers

Objects returned from Mongoose are not raw key-values like you might expect from the DB, but they have a lot of other functionality build in. Ultimately, cloneDeep does this, which ends up copying everything including functions and other stuff you may not want.

JSON.stringify as well as .toJSON will work because of the toJSON behavior.

So in fact they are not equivalent because you can redefine JSON serialization behavior and JSON never serializes functions anyway.

like image 161
Explosion Pills Avatar answered Nov 12 '22 16:11

Explosion Pills