通过键从数组中删除没有引用的对象

时间:2021-07-03 10:31:56

标签: javascript arrays list object find

我创建了一个空数组 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()),但它说许可证不是功能。

2 个答案:

答案 0 :(得分:0)

您可以使用 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))

答案 1 :(得分:0)

如果您想改变数组而不是使用 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);