asanas
asanas

Reputation: 4280

Keeping two arrays of objects separate in VueJS?

I have two arrays of objects:

  data: {
    a: [{"name":null}],
    b: [{"name":null}]
  },

And I have two methods. The first method adds an object to 'a'. And the second method, copies the entire 'a' to 'b.

  methods: {
    addNametoA() {
      this.a.push({"name":null})
    },
     CopyAtoB() {
      this.b = this.a
    }
  }

The problem is that once CopyAtoB() method is triggered, then whenever I add an object to a, it automatically copies it to b as well. This should not happen and how can I avoid it from happening?

Here is a jsbin showing this behavior.

https://jsbin.com/dojicasuqo/1/edit?html,js,console,output

Upvotes: 0

Views: 60

Answers (2)

Cloud Soh Jun Fu
Cloud Soh Jun Fu

Reputation: 1502

You can indeed do what Radu Diță was doing. However, the object inside the array is still getting referenced.

See example.

You should use below instead. To achieve complete unreferenced Object/Array.

copyAToBWithJson(){
  this.b = JSON.parse(JSON.stringify(this.a));
}

Upvotes: 0

Radu Diță
Radu Diță

Reputation: 14171

You are using the same array in both cases. You're passing a reference and not making a copy of the array.

You need to copy the array in CopyAToB(). Something like this:

this.b = [...this.a]

Upvotes: 1

Related Questions