Reputation: 1577
Let's say I want to delete a property in a JS object
const source = {
nestA: {
nestB: {
nestC: 'deleteMe'
}
}
}
const clone = {}
clone.nestA = {...source}.nestA
delete clone.nestA.nestB
console.log(source)
execute above script
expect: source
remain untouched
actual: source
will become {}
However, if I just do delete clone.nestA
, source
will remain untouched as expected
Question: How come delete clone.nestA.nestB
affect source
. But delete clone.nestA
doesn't?
Upvotes: 0
Views: 150
Reputation: 3036
You can use assign method of objects to create deep copy in that way your source can be untouchable.
let deepCopy = Object.assign({},source);
// do anything with deepCopy.
Update - It will not create a deep copy of nested object. You can use below method to create a deep copy for nested object.
let deepCopy = JSON.parse(JSON.stringify(source));
Or
function cloneObject(obj) {
var clone = {};
for(var i in obj) {
if(obj[i] != null && typeof(obj[i])=="object")
clone[i] = cloneObject(obj[i]);
else
clone[i] = obj[i];
}
return clone;
}
Check
Upvotes: 1
Reputation: 664528
How come
delete clone.nestA.nestB
affectssource
, butdelete clone.nestA
doesn't?
source
and clone
are distinct objects. A third object is referenced from both the source.nestA
property and the clone.nestA
property. (Another object is on the nestB
property of that).
When you delete a property on source
, like the source.nestA
property, you only affect the source
object.
When you delete a property on the third object, like source.nestA.nestB
or clone.nestA.nestB
(which is the same property on the same object), you only affect that third object. It's just that both source
and clone
now reference that object which misses a property.
Upvotes: 3