0

hello I have a list of projects listOfPhasesWithTasks which I get from backEnd. I assigned it to a local variable filteredPhasesWithTasks which I'm using in the rest of the project. It is supposed to work as a backup. When I'm doing filtering like this :

 this.filteredPhasesWithTasks.forEach((phase) => {
                    phase.tasks = phase.tasks.filter(task => task.taskName !== null && task.taskName.toUpperCase().includes(filterParam.taskName.toUpperCase()));
                });

I don't get why this changes my listOfPhasesWithTasks as well. I'm expecting that it would change only filteredPhasesWithTasks as code says.

mario
  • 186
  • 3
  • 16
  • You can solve this by instead using `Array.prototype.map` and returning new `phase` objects rather than modifying like `phase.tasks =`. You object spread `const newPhase = { ...phase };` to create new objects in combination with filter that also returns a new array. – Alexander Staroselsky May 29 '20 at 17:31
  • Can you create some sort of working example in StackBlitz including what the date roughly looks like and then I can try to help provide a solution – Alexander Staroselsky Jun 01 '20 at 13:15

1 Answers1

1

In Javascript (and Typescript) objects are passed by reference.

This means if you have an object and you assign it to a new one, you don't duplicate the object, you just have reference to the first object from both variables. Hence, changing a field in one of the variables you assigned "changes it for both". Actually, changes it to the only existing object that is pointed by both your variables :P

You could consider using the cloneDeep method offered by the library Lodash. You'll find a lot of other useful shortcuts there :)

Balastrong
  • 4,336
  • 2
  • 12
  • 31
  • Maybe show an example of how `Array.prototype.map` or similar can be used to avoid modifying the original/backup `phase` – Alexander Staroselsky May 29 '20 at 17:26
  • Thanks but I would rather not impleent new library into the Project :) I would prefer using Angular 7 method to do it, without any external library – mario Jun 01 '20 at 08:48