javascript Lodash 等效于 JSON.parse(JSON.stringify())
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25411826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lodash equivalent of JSON.parse(JSON.stringify())
提问by cyberwombat
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.
当我尝试 lodash 时 - 似乎推荐的方法是 cloneDeep() 但这对我来说完全是一团糟。我的对象部分由猫鼬查询的结果组成,这可能是导致这种情况的原因。
Original:
原来的:
template: 'email/receipt.swig',
templateVars: {
code: '299137819',
Cloneed with lodash:
用 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.
这里发生了什么?这显然是 Mongo 的东西,但为什么要重新格式化?有没有办法用 lodash 制作一个精确的副本?并不是说我目前的方法很痛苦——只是想了解为什么人们说 cloneDeep 是等价的。
回答by Explosion Pills
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.
从 Mongoose 返回的对象不是您可能从数据库中期望的原始键值,但它们内置了许多其他功能。最终,cloneDeep
这样做会复制所有内容,包括函数和您可能不想要的其他内容。
JSON.stringify
as well as .toJSON
will work because of the toJSON
behavior.
JSON.stringify
以及.toJSON
会因为toJSON
行为而起作用。
So in fact they are not equivalent because you can redefine JSON serialization behavior and JSON neverserializes functions anyway.
所以实际上它们并不等价,因为您可以重新定义 JSON 序列化行为,而 JSON无论如何都不会序列化函数。