Given array [{GUID, other properties}, ...],
How can I remove a specific object from a javascript array by its GUID (or any object property)?
I'm trying to use splice()
,
var index = game.data.collectedItems.indexOf(entityObj.GUID);
if (index > -1) {
game.data.collectedItems.splice(index, 1);
}
This won't work because I can't directly identify the value in the array, as such:
var array = [2, 5, 9];
var index = array.indexOf(5);
Shown here: How do I remove a particular element from an array in JavaScript?
I would recommend using the Array.prototype.filter
function, like this
game.data.collectedItems = game.data.collectedItems.filter(function(currentObj){
return currentObj.GUID !== entityObj["GUID"];
});
This would iterate through the elements of game.data.collectedItems
and filter out the items for which the function passed as a parameter, returns false
. In your case, all the objects will return true
except the object whose GUID
matches entityObj["GUID"]
.
Note: Since filter
creates a new Array, we need to replace the old array object with the new array object. That is why we are assigning the result of filter
back to game.data.collectedItems
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With