Reputation: 253
I have an array of objects (firstList), now I am creating a new array (exportData) by clone the array firstList, with this new array I want to delete some of its properties and I do the following:
let exportData = this.firstList;
exportData = exportData.filter(function (props) {
delete props.job;
return true;
});
Here I do not understand why even my old arrays are also deleting those properties, due to the mechanism or what did I do wrong?
Upvotes: 1
Views: 64
Reputation: 173
Your code is working the way it should.
let exportData = this.firstList;
you didn't create a new array , you just created one more reference to same array, it doesn't matter using which reference you are performing action because both are referring to same array.
If you try to clone in this way, it would be two different arrays,one copy of another and if there is any change on exportData, firstList will not be impacted.
let exportData = JSON.parse(JSON.stringify(this.firstList));
Upvotes: 0
Reputation: 5195
exportData is reference of firstList. so when something is changed in exportData, they will be reflected in firstList. so, you need to clone the array.
you can do:
let exportData = [];
for(var i =0; i < this.firstList.length; i++){
exportData[i] = this.firstList[i];
}
exportData = exportData.filter(function (props) {
delete props.job;
return true;
});
this is just a hint.
Upvotes: 0
Reputation: 222334
filter
is misused here because it doesn't actually filter anything, just iterates over array elements. For array iteration generic loop (for
, for..of
, forEach
) should be used.
The problem here is that props
object is not cloned. When it's modified, changes appear in every place where it's used.
The array should be mapped to shallow copies of objects where job
property is omitted. This can be conventionally done with spread and rest syntax:
exportData = exportData.map(({ job, ...props}) => ({...props}));
Upvotes: 1
Reputation: 4116
You're not creating a copy of the array, you're creating a new reference to the same array. You need to create a new array and populate if with copies of the objects, as in boran's answer.
Upvotes: 2
Reputation: 1819
let newexportData = exportData.map(function (props) {
let {job, ...other} = props;
return other;
});
Upvotes: 1