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));
};
Create Deep Copies with clonedeep Using the clonedeep function allows you to successfully create deep copies of objects.
Lodash's clone() function is a powerful utility for shallow cloning generic objects. The Object. assign() function or the spread operator are the canonical methods for shallow copying a POJO.
The cloneDeep method will iterate all levels of the original Object and recursively copying all properties found. The example I will give here is in Angular. Since we don't want to carry all the bundle of lodash to the client, we are going only to import the cloneDeep method.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With