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

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

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

当我尝试lodash – 似乎推荐的方式是cloneDeep(),但是这使我一塌糊涂。 我的对象部分由Mongoose查询的结果组成,这可能是导致此问题的原因。

原版的:

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

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

这里发生了什么? 这显然是Mongo的东西,但为什么重新格式化? 有没有办法用lodash做一个精确的副本? 不是说我目前的方法是一个痛苦 – 只是想明白为什么人们说cloneDeep是等价的。

从Mongoose返回的对象不是像你期望从数据库那样的原始键值,但是他们有很多其他的function。最后, cloneDeep做到了这一点 ,最终复制了包括函数和其他你不想要的东西在内的所有东西。

JSON.stringify以及.toJSON将因为toJSON行为而起作用。

所以实际上它们不是等价的,因为你可以重新定义JSON序列化行为,JSON 永远不会序列化函数。