0

I have the following click handler, when it is clicked I pull in an array from handsontable and then remove the last element from the array, and pass the new array to an ajax post. the issue is that if I click the button again it removes another item from the array. It seems like the data var is not being reset to all of the data on click?

$('#view-options').on('click', '#act_add', function() {

     var newData = $('#spreadsheet').handsontable("getData");
     var data = newData;
     newData.pop();
     console.log(newData);
     console.log(data);

     $.ajax({
        url: path + "api/v1/apps/add",
        data: {"data": newData},
        dataType: 'json',
        type: 'POST',
        success: function(res) {
           alertify.success("your data was added to the db");
        }
     });
  });

in the previous code newData and data both log the same array, this does not makes sense considering I only pop() the newData array

arrowill12
  • 1,784
  • 4
  • 29
  • 54
  • 1
    You assign 'newData' to 'Data', since that moment, both are the same object. – Airam May 06 '14 at 23:17
  • I am not doing the pop until after, wouldn't this mean that when i log them they will be different? – arrowill12 May 06 '14 at 23:18
  • Yeah, when you say `var data = newData;`, you're making data point to the same block of memory as newData, so when you make a change to that memory block, both will be affected. If you only want to affect one, you'd have to copy newData into data, not point data to newData. – Meredith May 06 '14 at 23:19

3 Answers3

1

When you did this:

var data = newData;

You set the pointer. So when you modify newData, data is modified too.

Use slice() function:

var data = [1, 2, 3, 4, 5];
var newData = data.slice();
newData.pop();
console.log(JSON.stringify(data));
console.log(JSON.stringify(newData));

Now you copied array (not created the pointer). So there are 2 different arrays, you can't change one of them and another array wouldn't be changed.

Sharikov Vladislav
  • 7,049
  • 9
  • 50
  • 87
0

When you assign a variable an object it assigns a reference to that object. So in this case newData and data point to the same object. Meaning any changes to data will necessarily change newData. You will have to make a copy of that object for what you're probably trying to achieve.

You can use this line instead of the assignment to copy the contents of the object:

var data = JSON.parse(JSON.stringify(newData));
sahbeewah
  • 2,690
  • 1
  • 12
  • 18
0

You're copying a javascript Object, so data receives a reference of the object newData. If you modify one of them, you'll modify the other.

there are sevral ways to copy a JSON object. the JSON.parse(JSON.strinify(newData)) trick is a solution but not very efficient and inner functions might not work properly after copy.

you'll find very good answers on how to copy these objects here and there.

Community
  • 1
  • 1
Xeltor
  • 4,626
  • 3
  • 24
  • 26