1

I have a function that takes a dynamic object and returns an object in angular typescript:

  public clean(row: object): object {
    //[... what to do here ? ]

    return row;
  }

This function should be able to take an object of any model / interface

Let's hypothetically assume I have the following data that I am passing through the function:

  this.data = {
    property1: 1,
    property2: 'prop2',
    property3: 'prop3',
    property4: 'prop4'
  }

And I would like the function "Clean" above to return the following:

  this.data2 = {
    property1: 1,
    property2: 'prop2',
    property3: 'prop3'
  }

In other words, I would like to remove property4 each time.

However, I would like this.data to be immutable, meaning I don't want to overwrite it, but I would like to return the new model without overwriting the old one (which is what my issue is now, it keeps overwriting it).

How would I do it ? I've tried to use the following:

let data2 = this.data;
delete data2['property4'];
return data2;

However, it's overwriting this.data.

Thanks for the help!

Heisenberg
  • 75
  • 1
  • 10

1 Answers1

3

Short Answer: shallow copy the object:

this.dataCopy = {...this.data};

Then you can delete the property as you are already doing.

Long answer:

Variables that are assigned with a non-primitive value (e.g not a string, not a number, not a symbol) are given a reference to that value. That reference points to the object’s location in memory. The variables don’t actually contain the value.

So when you are doing:

let data2 = this.data;

You are copying the reference (the pointer that points to where the object is stored in your memory), not the object! And every change to data2, will be reflected in this.data since they are both pointers to the same object!

In the short answer, I said shallow copy, why? Shallow copy because it will copy only the object properties but not any nested property. If you have an object with nested properties, you need to either declare explicitly the nested property to be copied or use another approach.

GBra 4.669
  • 1,512
  • 3
  • 11
  • 23