What is the best way to clone an object in node.js
e.g. I want to avoid the situation where:
var obj1 = {x: 5, y:5};
var obj2 = obj1;
obj2.x = 6;
con
This code is also work cause The Object.create() method creates a new object with the specified prototype object and properties.
var obj1 = {x:5, y:5};
var obj2 = Object.create(obj1);
obj2.x; //5
obj2.x = 6;
obj2.x; //6
obj1.x; //5
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.
Y'all suffering yet the solution is simple.
var obj1 = {x: 5, y:5};
var obj2 = {...obj1};
// Boom
Low-frills deep copy:
var obj2 = JSON.parse(JSON.stringify(obj1));
Attention: This solution is now marked as deprecated in the documentation of 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().
Original answer::
For a shallow copy, use Node's built-in util._extend()
function.
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
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;
};
Looking for a true clone option, I stumbled across ridcully's link to here:
http://my.opera.com/GreyWyvern/blog/show.dml/1725165
I modified the solution on that page so that the function attached to the Object
prototype is not enumerable. Here is my result:
Object.defineProperty(Object.prototype, 'clone', {
enumerable: false,
value: function() {
var newObj = (this instanceof Array) ? [] : {};
for (i in this) {
if (i == 'clone') continue;
if (this[i] && typeof this[i] == "object") {
newObj[i] = this[i].clone();
} else newObj[i] = this[i]
} return newObj;
}
});
Hopefully this helps someone else as well. Note that there are some caveats... particularly with properties named "clone". This works well for me. I don't take any credit for writing it. Again, I only changed how it was being defined.
Another solution is to encapsulate directly in the new variable using:
obj1= {...obj2}