【问题标题】:Remove object with no reference from array through a key通过键从数组中删除没有引用的对象
【发布时间】:2021-09-15 00:13:51
【问题描述】:
我创建了一个空数组playersList = [],当代码运行时它会被填充。
为了填充它,我使用:playersList.push({license, coins: playerCoins}),它正在工作。
我现在有这样的东西:
[
{
"license": "a123"
"coins": 100
}
{
"license": "b123"
"coins": 200
}
{
"license": "c123"
"coins": 100
}
]
我想知道如何通过它的许可证删除对象,因为它们没有参考。我在网上查看并尝试了index = playersList.findIndex(GetIdentifier(global.source, 'license').toString()),但它说许可它不是一个功能。
【问题讨论】:
标签:
javascript
arrays
list
object
find
【解决方案1】:
您可以使用Array.prototype.filter 删除对象
const bla = [{
license: "a123",
coins: 100
}, {
license: "b123",
coins: 200
}, {
license: "c123",
coins: 100
}]
const licenseToDelete = 'b123';
console.log(bla.filter(el => el.license !== licenseToDelete))
【解决方案2】:
如果您想改变数组而不是使用filter 获取新数组,您可以使用splice:
const arr = [
{
license: 'a123',
coins: 100
},
{
license: 'b123',
coins: 200
},
{
license: 'c123',
coins: 100
}
];
const licenseToDelete = 'c123';
// 1 means delete just one element
arr.splice(arr.findIndex(({license}) => license === licenseToDelete), 1);
console.log(arr);