Reputation: 604
I have the following code whose job is to remove specific properties from a JSON so that only some selected fields can be displayed in an a table
var tempColumnDefs = [];
var tempRowData = array;
for( var i = 0;i<columns.length;i++)
{
if(this.dynoArray[this.header[i]])
{tempColumnDefs.push(columns[i]);}
}
for( var i = 0;i<tempRowData.length;i++)
{
for(var j = 0;j<this.header.length;j++)
{
if(!this.dynoArray[this.header[j]])
{
delete tempRowData[i][this.header[j]];
}
}
}
this.cols = tempColumnDefs;
this.cars = tempRowData;
As you can see "array" is never on the left hand side so it shouldn't be updated at any case,only "tempRowData" should, but it somehow updates array too.
Upvotes: 0
Views: 693
Reputation:
You can also try copying the array using the '...' operator.
var tempRowData = [...array];
this does exactly what you want to do, i.e. copy each element one by one. the
...array
will hold out the elements of the array for you. And putting it inside a
[ ];
will give you an array with the same elements but a different array binding.
BEWARE: Both the copying by loop and the ... method will still copy the elements by reference. Which means Mutating(adding deleting elements) the array might not have any effect on the original, but in case of object elements, changing any element's properties will affect the element in the original array.
Upvotes: 2
Reputation: 5709
This is probably because with this instruction:
var tempRowData = array;
you are making two variables that point to the same memory address, so updating one will update also the other one.
You need to create a new array and copy each value of the old array into the new one.
Generally primitive data are passed by value, non primitive data are passed by reference
Upvotes: 1