[英]filter an array of objects based on key/value and remove it from array
在下面的函數中,我將對象推到accountsToDelete
數組,然后需要從accountsToAdd
數組中刪除匹配的對象。 我猜我將不得不使用IndexOf,Filter,Reduce的組合,但是在理解如何實現這一點上我仍然有些粗略。 這是當前功能:
accountDelete(id, name) {
const accountsToAdd = this.userForm.value.accountsToAdd;
const accountsToDelete = this.userForm.value.accountsToDelete;
this.userForm.value.accountsToDelete.push(
{
id: id,
name: name
}
);
}
您可以簡單地使用過濾器功能。 可以這樣說,應該在accountToAdd
中過濾所有條目,該id
適合要刪除的帳戶。
一個例子:
// Initialize both lists.
let accountsToAdd = []
let accountsToDelete = []
// Preparation by adding a account to the first list.
const account = { id: 1, name: 'Max' }
accountsToAdd.push(account)
// Mark account to be removed.
accountsToDelete.push(account)
accountsToAdd = accountsToAdd.filter(acc => acc.id !== account.id)
// Verify result.
console.log(accountsToAdd)
console.log(accountsToDelete)
注意:
您的兩個列表都定義為常量。 這樣,您將無法使用重新分配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.