当我运行下面的代码时,listData(原始数据源)也将受到影响。
如何改善代码,以便downloadData可以从listData复制数据并删除数组中的id,createBy,create_at,updatedBy和updated_at,但listData的数据将保留且未更改?
let downloadData = this.listData.filteredData;
let downloadDataNum = downloadData.length;
for( let i = 0; i < downloadDataNum; i++ ) {
delete downloadData[i].id;
delete downloadData[i].createdBy;
delete downloadData[i].created_at;
delete downloadData[i].updatedBy;
delete downloadData[i].updated_at;
}
答案 0 :(得分:3)
您可以尝试使用"..."
深拷贝
let downloadData = [...this.listData.filteredData];
let downloadDataNum = downloadData.length;
for( let i = 0; i < downloadDataNum; i++ ) {
delete downloadData[i].id;
delete downloadData[i].createdBy;
delete downloadData[i].created_at;
delete downloadData[i].updatedBy;
delete downloadData[i].updated_at;
}
让我知道它是否有效。
答案 1 :(得分:2)
let downloadData = [...this.listData.filteredData];
for( let i = 0; i < downloadData.length; i++ ) {
delete downloadData[i].id;
delete downloadData[i].createdBy;
delete downloadData[i].created_at;
delete downloadData[i].updatedBy;
delete downloadData[i].updated_at;
}
您可以尝试...使用传播运算符,您可以将数据传播到downloadData变量,而无需更改listData
答案 2 :(得分:1)
您应该使用JSON.stringify()
和JSON.parse()
let downloadData = JSON.parse(JSON.stringify(this.listData.filteredData));
您还可以使用forEach
键数组来简化代码。
let keys = ['id','createdBy','created_at','updatedBy','updated_at'];
downloadDataNum.forEach(x => {
keys.forEach(key => delete x[key]);
})
map()
和reduce()
您可以在原始数组上使用map()
并返回包含所需属性的新数组
let keys = ['id','createdBy','created_at','updatedBy','updated_at'];
let downloadData = this.listData.filteredData.map(x => {
return keys.reduce((ac,a) => (ac[a] = x[a],ac),{})
});
答案 3 :(得分:1)
在编辑数组之前先对其进行克隆,因为数组是通过引用复制的:
let downloadData = this.listData.filteredData;
// Clone the array
let cloneDownloadData = downloadData.slice(0);
let downloadDataNum = cloneDownloadData.length;
for( let i = 0; i < downloadDataNum; i++ ) {
delete cloneDownloadData[i].id;
delete cloneDownloadData[i].createdBy;
delete cloneDownloadData[i].created_at;
delete cloneDownloadData[i].updatedBy;
delete dcloneDownloadData[i].updated_at;
}
答案 4 :(得分:1)
您必须复制原始数据。
您可以通过以下几种方法执行此操作:
// Way 1
let downloadData = Array.from(this.listData.filteredData);
// Way 2
let downloadData = JSON.parse(JSON.stringify(this.listData.filteredData));
// Way 3 (using spread operator)
let downloadData = [...this.listData.filteredData];
// Way 4
let downloadData = this.listData.filteredData.slice(0);
那么您添加到downloadData
的任何修改都不会影响原始数据。