根据键/值过滤对象数组并将其从数组中删除

时间:2018-03-15 14:17:17

标签: javascript

在下面的函数中,我推送并反对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
        }
    );
}

1 个答案:

答案 0 :(得分:1)

您只需使用https://jsfiddle.net/9wxw85r0/3/功能即可。您可以这样说,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)


注意:
您的两个列表都定义为常量。这样你就无法使用重新分配。