[英]Delete object from array of multiple objects
我有一個像這樣的數組:
var participants = [
{username: "john", time: null},
{username: "samira", time: null},
{username: "mike", time: null},
{username: "son", time:null}
]
我想通過用戶名刪除項目:
const index = participants.map(x => {
x.map(y => {
return y.username;
})
}).indexOf(username); //get index of username
participants.splice(index, 1);
因此,用戶名的索引返回“ -1”,因此參與者數組變為0?
預期的輸出,按用戶名:“ son”:
[
{username: "john", time: null},
{username: "samira", time: null},
{username: "mike", time: null}
]
更新:
原來我的數組在數組中,像這樣
您可以使用數組過濾器功能
participants.filter((item) => item.username !== username))
嘗試這個
var username = 'son';
for(var i = 0; i < participants.length; i++) {
if(participants[i].username == username) {
participants.splice(i, 1);
i--;
}
}
注意: filter
, map
等提供了代碼可讀性,而for
循環則表現更好。 根據您的具體問題進行選擇。
您可以使用過濾器方法,也可以使用splice和map:
participants.splice(participants.map(x => x.username).indexOf(username),1);
您可以使用過濾器功能,但過濾器不會更改原始數組; 因此您必須將結果重新分配給原始變量。 參與者= partners.filter((item)=> item.username!==用戶名))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.