0

variable x is assigned to variable y in angular, whenever variable x changes y is also getting changed. how to prevent that?

ngOnInit() {
this.editFunction()
}

editFunction(){
 for (let i = 0; i < this.editingData["tags"].length; i++) {
        this.existingTagsDropDown.push(editingData["tags"][i].tag_id);
        this.existingTagsChip.push({
          value: editingData["tags"][i].tag_id,
          viewValue: editingData["tags"][i].name,
        });
      }
      this.existingTags = this.existingTagsChip;
}

addNewTags(){
 for (let i = 0; i < this.selectedButtonOptions.length; i++) {
        this.existingTagsChip.push({
          value: this.selectedButtonOptions[i].value,
          viewValue: this.selectedButtonOptions[i].viewValue,
          });
      }
}

existingTags is getting updated whenever existingTagsChip is updated. How to prevent that

Sulu
  • 1
  • 1
  • Does this answer your question? [Why does changing an Array in JavaScript affect copies of the array?](https://stackoverflow.com/questions/6612385/why-does-changing-an-array-in-javascript-affect-copies-of-the-array) – Heretic Monkey May 16 '23 at 12:39
  • `existingTags` is assigned by reference, not by value. You can use spread operator like `this.existingTags = [...this.existingTagsChip]` but this will not solve your issue if you want a totally independent array of tags. I mean, even though you "clone" the array, you still have the same references of the tags in each array. If that's the case, you can use [`cloneDeep()`](https://www.geeksforgeeks.org/lodash-_-clonedeep-method/) from `lodash` – Harun Yilmaz May 16 '23 at 12:40

1 Answers1

0

That is how Js/Ts are working. If the value is primitive (number,string, boolean, etc..) simple solution a=b would work. But if you deal with structured data types, language engines create references to memory, so if you do a=b a will have just a reference to the object b and if you change it will also change a.

If you want to copy value of b to a you could do this:

  1. Way #1:

    Deep copy by serializing object (NOTE Works only with json safe data):

    let a = { foo: { bar: 'baz' } }; 
    let b = JSON.parse(JSON.stringify(a));
    
  2. Way #2:

    Spread operator (Works only with arrays and objects. Also as @harun-yilmaz mentioned, this still is not a 'true copy'):

    let a = [1,2,3]; 
    let b = [...a];
    

    or

    let a = { foo: { bar: 'baz' } }
    let b = {...a}
    
  3. Way #3:

    Object.asing() method (NOTE: It creates a shallow copy, which means it will 'true' copy only values that are not nested. For nested values it will use reference to them):

    let a = { foo: { bar: 'baz' } } 
    let b = Object.asign({},a)