0
 async create() {
      let formData = new FormData()
      formData.append('name', this.name)
      formData.append('size', JSON.stringify(this.size))
      let copy = [...this.layers] // <==== HERE I TRY TO COPY 
      copy.forEach((layer, layerIndex) => {
        layer.traits.forEach((trait, traitIndex) => {
          if (!(trait.file instanceof Blob)) return
          let name = `file_${layerIndex}_${traitIndex}`
          formData.append(`images`, trait.file, name)
          trait.file = name
        })
      })
      formData.append('layers', JSON.stringify(copy))
      try {
        let result = await this.$axios.$post('/api/createcollection', formData)
        this.$router.push('/dashboard')
      } catch (err) {
        this.layers = [...copy] // <==== HERE I RESET IT IF ITS FAIL
        this.message = err.response.data
        setTimeout(() => {
          this.message = ''
        }, 5000)
      }
    },

I am not able to set this.layers to the way it was before. I have sent it, but for some reason, copy is the same value as this.layers

Why this is copying the same as this.layers even if I spread it into a new array?

double-beep
  • 5,031
  • 17
  • 33
  • 41
bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • 6
    The copy is a **shallow** copy. Both arrays will refer to the same (original) objects. – Pointy Sep 21 '21 at 13:35
  • 3
    The array is a copy. If you manipulate the array, it won't affect the other array. But you are manipulating _other objects_ that are referenced in the array and not the array itself, and you didn't copy these objects! – CherryDT Sep 21 '21 at 13:39
  • the spread operator is a shallow copy. so if you have nested arrays inside your array, those will be copied with reference. any changes you make in the copy, will also appear in the original one. One way to de a deep clone is to use JSON.parse/JSON stringify clonedArray = JSON.parse(JSON.stringify(originalArray)) This way your copy should be a real clone. Generally, be aware that this method also has issues. Nested objects containing functions will not copy the function and new Date() values will be copied as string. – J_K Sep 21 '21 at 13:55
  • @J_K i cant just stringify it, i have files in it – bill.gates Sep 21 '21 at 13:57

0 Answers0