Reputation: 5958
I have
config.default_req = { foo: 'foo' }
this.default_req = _.clone(config.default_req);
this.default_req.body.data = 'bar';
Now config.default_req.data
equals to 'bar', why?, I thought cloning with lodash is supposed to just copy the object, losing any link to the original one!
Any idea of how to really clone/copy an object in node.js? (v.0.10.40)
Edit: For those who will get to this question, a simple clone/copy function:
var clone = function(source){
return JSON.parse(JSON.stringify(source));
};
Upvotes: 16
Views: 24046
Reputation: 4499
This because clone
is shallow copy. You should be using cloneDeep
.
Check the Reference here: https://lodash.com/docs#cloneDeep
A shallow copy will only copy over data on each property of the object. So arrays and objects are passed by reference. A shallow copy is relatively fast. A deep copy on the other hand recursively goes down the tree, so objects and arrays are new instances. Deep copies are relatively slow, so be weary of using them unless needed.
You can check it out in a fiddle here: https://jsfiddle.net/qqnved24/2/
Try playing around with the following:
var myObj = {
arr: [1, 2, 3],
obj: {
first: 'foo'
}
}
var myDeepClone = _.cloneDeep(myObj)
var myShallowClone = _.clone(myObj)
//Should ONLY change array slot 1 on my Clone
myDeepClone.arr[1] = 99
console.log(' ==== Checking Deep Clone Array ==== ')
console.log(myObj)
console.log(' -- Deep Clone Below --');
console.log(myDeepClone)
console.log('\n\n')
// Danger: Will change the 'first' property on both the shallow copy and the original
myShallowClone.obj.first = 'bar';
console.log(' ==== Checking Shallow Clone Obj ==== ')
console.log(myObj)
console.log(' -- Shallow Clone Below --');
console.log(myShallowClone);
console.log('\n\n')
// Should only change the 'first property' on the Deep Cloned Obj
myDeepClone.obj.first= 'myObj';
console.log(' ==== Checking Deep Clone Obj ==== ')
console.log(myObj)
console.log(' -- Deep Clone Below --');
console.log(myDeepClone)
console.log('\n\n')
// Danger will alter Shallow clones OBJ
myObj.obj.meaningOfLife = 42;
console.log(' ==== Mutating Original Obj ==== ')
console.log(myObj)
console.log(' -- Shallow Clone Below --');
console.log(myShallowClone)
console.log(' -- Deep Clone Below --');
console.log(myDeepClone)
Upvotes: 28