Lodash相当于JSON.parse(JSON.stringify())

cyb*_*bat 5 javascript node.js lodash

我目前正在克隆一个对象:

var copy = JSON.parse(JSON.stringify(original));
Run Code Online (Sandbox Code Playgroud)

当我尝试lodash时 - 似乎推荐的方法是cloneDeep(),但这对我来说总是一团糟.我的对象部分由Mongoose查询的结果组成,这可能是造成这种情况的原因.

原版的:

template: 'email/receipt.swig',
templateVars: { 
  code: '299137819',
Run Code Online (Sandbox Code Playgroud)

用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'
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?这显然是Mongo的东西,但为什么重新格式化?有没有办法用lodash制作精确的副本?并不是说我当前的方法很痛苦 - 只是试图理解为什么人们说cloneDeep是等价的.

Exp*_*lls 2

从 Mongoose 返回的对象并不是像您从数据库中期望的那样的原始键值,但它们内置了许多其他功能。最终,cloneDeep执行此操作,最终会复制所有内容,包括函数和您可能不想要的其他内容。

JSON.stringify也会因为这种.toJSON行为而起作用。toJSON

所以实际上它们并不等同,因为您可以重新定义 JSON 序列化行为,而 JSON无论如何都不会序列化函数。