LeO
LeO

Reputation: 5258

Typescript: Object.assign - shallow or deep copy for delete

I have an object with a structure like data.edit.lstAnnotation.lstComments with

...
lstAnnotation?: AnnotationInterface;
...
export interface AnnotationInterface {
  lstComments: CommentList;
}
export class CommentList {
  [key: string]: CommentEntity;
}
...

To my understanding the function Object.assign() makes a shallow copy. Which means that the content is not copied and the references are maintained. I have a function like

Object.keys(this.data.edit.lstAnnotation.lstComments).map((key: string) => {
      const newEntity = {...this.data.edit.lstAnnotation.lstComments[key]};
      delete newEntity.cur; // <<<<----------------- [1]
      if (newEntity.add && newEntity.add.trim().length === 0) {
        delete newEntity.add;  // <<<<-------------- [2]
      }
      return JSON.stringify(newEntity);
    }).join();

which makes a nice string. To my understanding I create a shallow copy of the content and then remove (delete) properties. My question is, why is the delete not applied to the original list (data.edit.lstAnnotation.lstComments)?

I have still in data.edit.lstAnnotation.lstComments entries with the key cur, e.g. data.edit.lstAnnotation.lstComments['abc'].cur ==> object....

I'm quite happy with the current situation. But if I delete from the copied object and the orginal isn't updated I would say this is a deep copy. So, where is my mistake?

Upvotes: 0

Views: 1522

Answers (1)

kaya3
kaya3

Reputation: 51102

Here's some example code which demonstrates the core issue:

const array = [1, 2, 3];
const original = {a: array, b: 4};
const copy = {};
Object.assign(copy, original);
delete copy.a;

What happens:

  • An array containing 1, 2, 3 is created, and array holds a reference to it.
  • An object is created with the property a holding a reference to the array, and the property b holding the value 4, and original holds a reference to the new object.
  • An object is created with no properties, and copy holds a reference to it.
  • Object.assign makes a shallow copy of the object original refers to, into the object copy refers to. This is a shallow copy, so copy.a is now a reference to the same array that original.a is a reference to; no copy of the array is made.
  • The a property belonging to the object that copy refers to is deleted, so that object no longer has a property named a. The object original refers to still has its own property named a, because it is a different object.

It may help you to understand by stepping through the execution using the excellent Javascript Tutor tool, which shows visually what happens to the program state as each line is executed.

Upvotes: 1

Related Questions