0

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?

JSNoob
  • 1,477
  • 2
  • 18
  • 31

2 Answers2

3

How come delete clone.nestA.nestB affects source, but delete 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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

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

Abhinav Kumar
  • 2,883
  • 1
  • 17
  • 30
  • Not true from what I can see. If you run this, it behaves the same way as the spread example: `const source = { nestA: { nestB: { nestC: 'deleteMe' } } }; const clone = Object.assign({}, source); delete clone.nestA.nestB; console.log(source);` – jmcgriz Sep 10 '18 at 20:43