0

There was a problem with Vue JS - 2 empty arrays are declared in data. At the beginning of the work, I fill array A with a hundred nested arrays. Later, during the user’s action (clicking on the rendered element), I need to take from the array A the element corresponding to the clicked block and “expand” for the user so that he can edit all of his fields. To do this, I take an empty array B and assign it the target element of array A. And then, through v-for, I draw inputs from v-model from the contents of array B.

The problem is the following - after I equated array B with an element of array A, they seem to be connected and any change in an element of array B entails an identical change in the nested array A.

I can not find a solution, where to look? It is necessary that array B be just a copy of an element of array A and live its own life.

Example

var app = new Vue ({
          el: '#app',
          data: {
            array_1: [['22', '43', '12'], ['tg', 'gf', 'fc'], ['fff', 'iii', 'ppp']],
            array_2: []
          },
          methods: {
          start_edit (arr) {
            app.array_2 = arr;
            }
          }

        });

when clicked, the start_edit () method is called with the clicked element as an argument. Suppose it was like this:

start_edit (array_1 [2])

then I change something in array_2 and it also immediately changes in array_1 [2];

How to avoid this?

1 Answers1

0

You're copying the original array by reference, meaning the two arrays are pointing to the same place in memory, ie they're both the same array. You want to copy by value. In your case, you would want to do array_2 = JSON.parse(JSON.stringify(arr)). More on that here https://stackoverflow.com/a/23536726/3401008

dyslexit
  • 689
  • 1
  • 9
  • 18