0

I made an empty arrayy playersList = [] that gets filled as the code runs. To fill it I use: playersList.push({license, coins: playerCoins}), which it's working.

I now have something like this:

[
  {
    "license": "a123"
    "coins": 100
  }
  {
    "license": "b123"
    "coins": 200
  }
  {
    "license": "c123"
    "coins": 100
  }   
]

I would like to know how can I remove an object through it's license, as they have no reference. I've looked online and tried index = playersList.findIndex(GetIdentifier(global.source, 'license').toString()) but it says license it's not a function.

  • Does this answer your question? [How do I remove an object from an array with JavaScript?](https://stackoverflow.com/questions/3396088/how-do-i-remove-an-object-from-an-array-with-javascript) or see: [Remove Object from Array using JavaScript](https://stackoverflow.com/questions/10024866/remove-object-from-array-using-javascript) – pilchard Jul 03 '21 at 10:40

2 Answers2

0

You can use Array.prototype.filter to remove the object

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))
Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32
0

If you want to mutate the array instead of getting a new one by using filter, you can use 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);
tam.teixeira
  • 805
  • 7
  • 10