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
npm install node-v8-clone
Fastest cloner, it open native clone method from node.js
var clone = require('node-v8-clone').clone;
var newObj = clone(obj, true); //true - deep recursive clone
I'm surprised Object.assign
hasn't been mentioned.
let cloned = Object.assign({}, source);
If available (e.g. Babel), you can use the object spread operator:
let cloned = { ... source };
You can use the extend function from JQuery:
var newClone= jQuery.extend({}, oldObject);
var deepClone = jQuery.extend(true, {}, oldObject);
There is a Node.js Plugin too:
https://github.com/shimondoodkin/nodejs-clone-extend
To do it without JQuery or Plugin read this here:
http://my.opera.com/GreyWyvern/blog/show.dml/1725165
Check out underscore.js. It has both clone and extend and many other very useful functions.
This can be useful: Using the Underscore module with Node.js
You can prototype object and then call object instance every time you want to use and change object:
function object () {
this.x = 5;
this.y = 5;
}
var obj1 = new object();
var obj2 = new object();
obj2.x = 6;
console.log(obj1.x); //logs 5
You can also pass arguments to object constructor
function object (x, y) {
this.x = x;
this.y = y;
}
var obj1 = new object(5, 5);
var obj2 = new object(6, 6);
console.log(obj1.x); //logs 5
console.log(obj2.x); //logs 6
Hope this is helpful.
You can also use SugarJS in NodeJS.
http://sugarjs.com/
They have a very clean clone feature: http://sugarjs.com/api/Object/clone