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
There is also a project on Github that aims to be a more direct port of the jQuery.extend()
:
https://github.com/dreamerslab/node.extend
An example, modified from the jQuery docs:
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);
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
Looks like it handles all kinds of stuff, including circular references. From the github page:
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!
If you're using coffee-script, it's as easy as:
newObject = {}
newObject[key] = value for own key,value of oldObject
Though this isn't a deep clone.