[英]Javascript trying to remove items from a nested array and re-assigning to state without success
boxIds
=> 接收到的唯一文件 ID 數組。cluster
都有一個files
數組。我正在尋找遍歷每個集群並尋找匹配的文件 id,如果該 id 存在,則從該特定集群中刪除該文件。
出於某種原因,我在使用splice()
時得到了錯誤的結果,因為它正在改變原始數組,這會創建一個返回數組並刪除所有其他文件的結果。
moveFilesToCluster: function(state,payload){
const boxIds = payload.boxIds;
const moveToClusterId = payload.clusterId;
let fileAddToCluster = [];
state.assignmentClusters.forEach(cluster =>{
cluster.files.slice().forEach((file,index) =>{
if (_.includes(boxIds, file.id)){
fileAddToCluster.push(file);
cluster.files.splice(index,1)
}
});
});
}
我還嘗試(在此代碼中)在forEach()
slice()
) (見上文),但這並沒有真正交付。
我還嘗試(在此代碼中)在 forEach() 之前添加 slice() (見上文),但這並沒有真正交付。
正如我在評論中所說,我發現這不起作用令人驚訝。 在您的問題中使用slice
克隆cluster.files
然后遍歷克隆,並且您正在修改原始文件。 那應該行得通。 這不是我推薦的方式,但它應該可以工作。
執行此操作的經典方法是使用filter
:
const boxIds = payload.boxIds;
const moveToClusterId = payload.clusterId;
let fileAddToCluster = [];
state.assignmentClusters.forEach(cluster =>{
cluster.files = cluster.files.filter(file) {
if (_.includes(boxIds, file.id)){
fileAddToCluster.push(file);
return false;
}
return true;
});
});
但是如果你想修改數組,你可以使用一個無聊的老while
循環,如果你不刪除條目,只增加索引:
const boxIds = payload.boxIds;
const moveToClusterId = payload.clusterId;
let fileAddToCluster = [];
state.assignmentClusters.forEach(cluster =>{
let i = 0;
while (i < cluster.files.length) {
if (_.includes(boxIds, file.id)){
fileAddToCluster.push(file);
cluster.files.splice(i, 1);
} else {
++i;
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.