0

I have the following method compares two array, one coming from the props and the other one from my own component. Every element that exists in my props array but doesnt exist in my components array is inserted in a third array with the added property called "destroy : true" so i can send it to the back end to be deleted from the database.

However for whatever reason my props is being updated instead of the variables i use in the method to do all this. i am not really sure why since i am not referencing the prop directly but i do copy its content to the variables in the method.

     updateArray(){
        let updatedArray = []
        let oldArray = [...this.props.array]
        oldArray.forEach(element => {
          if(this.componentArray.indexOf(element) > -1){
            updatedArray.push(element)
          }else{
            let newElement = element
            newElement.destroy = true
            updatedArray.push(newElement)
          }
        })
       return updatedArray 
},

why does this happen exactly? every other element in my component works fine except this.

1 Answers1

1

Yes, you are copying the elements of the this.props.array array into a new array local to the method but given that the elements of the array are objects, both arrays are in the end containing same objects (references to the objects)

You can create shallow copy of the original element with the spread operator let newElement = { ...element } - this creates the completely new object and copy all properties of the original object. But be aware that if any property of original objects contains array/object, you have the same problem... just one level down

Michal Levý
  • 33,064
  • 4
  • 68
  • 86