Changes applied to copied row affected original row

Changes applied to copied row affected original row

vietcodervietcoder Posts: 2Questions: 1Answers: 0

Hi,
I'm using the following code to copy data from an existing row to create a new row:
function copyRow(td) {
var row = myTable.row( $(td).parents('tr') ).data();
var newRow = myTable.row.add(row).draw(false);
}

However, whenever I updated any cell on the copied row, it also affected the underlying data of the original row as well. For example, if I do something like:
$('#myTable tbody').on('click', 'td', function () {
myTable.cell(this).data("some_new_value");
});

Let's say td is a cell in the copied row, the td at the same column in the original row is also updated if I tried to access the value for the cell of the original row using something like $(original_td).data() (the value for the original row becomes "some_new_value" now). Just to be clear, the data shown on the browser still looks good, it didn't change the displayed value of the original cell. However, accessing the original cell's value using data() is showing the same value as the copied cell's.

Answers

  • vietcodervietcoder Posts: 2Questions: 1Answers: 0

    I figured out what the problem is. This is because Javascript object is just a reference. When I updated the reference, I ended up updating the original as well. I had to use the Object.assign() method to get a shallow copy and that solved the issue.

This discussion has been closed.