Javascript 在 Node.js 中克隆一个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5055746/
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
Cloning an Object in Node.js
提问by slifty
What is the best way to clone an object in node.js
在 node.js 中克隆对象的最佳方法是什么
e.g. I want to avoid the situation where:
例如,我想避免以下情况:
var obj1 = {x: 5, y:5};
var obj2 = obj1;
obj2.x = 6;
console.log(obj1.x); // logs 6
The object may well contain complex types as attributes, so a simple for(var x in obj1) wouldn't solve. Do I need to write a recursive clone myself or is there something built in that I'm not seeing?
该对象很可能包含复杂类型作为属性,因此简单的 for(var x in obj1) 无法解决。我是否需要自己编写递归克隆,还是有一些我没有看到的内置内容?
回答by jimbo
Possibility 1
可能性 1
Low-frills deep copy:
低装饰深拷贝:
var obj2 = JSON.parse(JSON.stringify(obj1));
Possibility 2 (deprecated)
可能性 2(已弃用)
Attention:This solution is now marked as deprecated in the documentation of Node.js:
注意:此解决方案现已在Node.js 文档中标记为已弃用:
The util._extend() method was never intended to be used outside of internal Node.js modules. The community found and used it anyway.
It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign().
util._extend() 方法从未打算在内部 Node.js 模块之外使用。社区无论如何都找到并使用了它。
它已被弃用,不应在新代码中使用。JavaScript 通过 Object.assign() 提供了非常相似的内置功能。
Original answer::
原答案::
For a shallow copy, use Node's built-in util._extend()
function.
对于浅拷贝,使用 Node 的内置util._extend()
函数。
var extend = require('util')._extend;
var obj1 = {x: 5, y:5};
var obj2 = extend({}, obj1);
obj2.x = 6;
console.log(obj1.x); // still logs 5
Source code of Node's _extend
function is in here: https://github.com/joyent/node/blob/master/lib/util.js
Node_extend
函数的源代码在这里:https: //github.com/joyent/node/blob/master/lib/util.js
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || typeof add !== 'object') return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
回答by djanowski
I'm surprised Object.assign
hasn't been mentioned.
我很惊讶Object.assign
没有被提及。
let cloned = Object.assign({}, source);
If available (e.g. Babel), you can use the object spread operator:
如果可用(例如 Babel),您可以使用对象扩展运算符:
let cloned = { ... source };
回答by Michael Dillon
Object.defineProperty(Object.prototype, "extend", {
enumerable: false,
value: function(from) {
var props = Object.getOwnPropertyNames(from);
var dest = this;
props.forEach(function(name) {
if (name in dest) {
var destination = Object.getOwnPropertyDescriptor(from, name);
Object.defineProperty(dest, name, destination);
}
});
return this;
}
});
This will define an extend method that you can use. Code comes from this article.
这将定义一个您可以使用的扩展方法。代码来自这篇文章。
回答by user2516109
var obj2 = JSON.parse(JSON.stringify(obj1));
回答by ridcully
You can use the extend function from JQuery:
您可以使用 JQuery 的扩展功能:
var newClone= jQuery.extend({}, oldObject);
var deepClone = jQuery.extend(true, {}, oldObject);
There is a Node.js Plugin too:
还有一个 Node.js 插件:
https://github.com/shimondoodkin/nodejs-clone-extend
https://github.com/shimondoodkin/nodejs-clone-extend
To do it without JQuery or Plugin read this here:
要在没有 JQuery 或插件的情况下执行此操作,请在此处阅读:
回答by esp
Check out underscore.js. It has both cloneand extendand many other very useful functions.
查看underscore.js。它具有克隆和扩展以及许多其他非常有用的功能。
This can be useful: Using the Underscore module with Node.js
回答by Clint Harris
There are some Node modules out there if don't want to "roll your own". This one looks good: https://www.npmjs.com/package/clone
如果不想“推出自己的”,还有一些 Node 模块。这个看起来不错:https: //www.npmjs.com/package/clone
Looks like it handles all kinds of stuff, including circular references. From the githubpage:
看起来它处理各种东西,包括循环引用。从github页面:
clone masters cloning objects, arrays, Date objects, and RegEx objects. Everything is cloned recursively, so that you can clone dates in arrays in objects, for example. [...] Circular references? Yep!
clone 大师克隆对象、数组、Date 对象和 RegEx 对象。例如,所有内容都是递归克隆的,因此您可以在对象的数组中克隆日期。[...] 循环引用?是的!
回答by Hiron
This code is also work cause The Object.create()method creates a new object with the specified prototype object and properties.
这段代码也是有效的,因为Object.create()方法创建了一个具有指定原型对象和属性的新对象。
var obj1 = {x:5, y:5};
var obj2 = Object.create(obj1);
obj2.x; //5
obj2.x = 6;
obj2.x; //6
obj1.x; //5
回答by nihil
Simple and the fastest way to clone an Object in NodeJS is to use Object.keys( obj ) method
在 NodeJS 中克隆对象的简单且最快的方法是使用 Object.keys( obj ) 方法
var a = {"a": "a11", "b": "avc"};
var b;
for(var keys = Object.keys(a), l = keys.length; l; --l)
{
b[ keys[l-1] ] = a[ keys[l-1] ];
}
b.a = 0;
console.log("a: " + JSON.stringify(a)); // LOG: a: {"a":"a11","b":"avc"}
console.log("b: " + JSON.stringify(b)); // LOG: b: {"a":0,"b":"avc"}
The method Object.keys requires JavaScript 1.8.5; nodeJS v0.4.11 supports this method
Object.keys 方法需要 JavaScript 1.8.5;nodeJS v0.4.11 支持此方法
but of course for nested objects need to implement recursive func
但当然嵌套对象需要实现递归函数
Other solution is to use native JSON (Implemented in JavaScript 1.7), but it's much slower (~10 times slower) than previous one
其他解决方案是使用本机 JSON(在 JavaScript 1.7 中实现),但它比以前的要慢得多(慢约 10 倍)
var a = {"a": i, "b": i*i};
var b = JSON.parse(JSON.stringify(a));
b.a = 0;
回答by Randy
There is also a project on Github that aims to be a more direct port of the jQuery.extend()
:
Github 上还有一个项目旨在成为以下项目的更直接端口jQuery.extend()
:
https://github.com/dreamerslab/node.extend
https://github.com/dreamerslab/node.extend
An example, modified from the jQuery docs:
一个例子,从jQuery 文档修改:
var extend = require('node.extend');
var object1 = {
apple: 0,
banana: {
weight: 52,
price: 100
},
cherry: 97
};
var object2 = {
banana: {
price: 200
},
durian: 100
};
var merged = extend(object1, object2);