我目前正在克隆一个对象:
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 返回的对象不是您可能期望从数据库中获得的原始键值,但它们内置了许多其他功能。最终,cloneDeep
does this ,最终会复制所有内容,包括您可能不需要的功能和其他内容。
JSON.stringify
和 .toJSON
都可以使用 because of the toJSON
行为。
所以实际上它们并不等价,因为您可以重新定义 JSON 序列化行为,而 JSON 从不无论如何都不会序列化函数。
关于javascript - 相当于 JSON.parse(JSON.stringify()) 的 Lodash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25411826/