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

23,137

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.

Share:
23,137
cyberwombat
Author by

cyberwombat

My name is Yashua (@cyberwombat) and I am a full stack JS developer with a penchant for pixel perfect design and cutting edge tech. I am the cofounder and lead tech of LotusEngine, an automation and state machine platform. I thrive on co-creating and exploring potential ideas and helping people implement them whether through consultation or direct involvement. I am primarily based in Northern Arizona but travel often. I can equally assist you through online communication or meet you in person should our locations coincide.

Updated on August 21, 2020

Comments

  • cyberwombat
    cyberwombat over 3 years

    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.