Find and remove objects in an array based on a key value in JavaScript
Here is a solution if you are not using jQuery:
myArray = myArray.filter(function( obj ) {
return obj.id !== id;
});
I can grep the array for the id, but how can I delete the entire object where id == 88
Simply filter by the opposite predicate:
var data = $.grep(data, function(e){
return e.id != id;
});
You can simplify this, and there isn't really any need for using jQuery here.
var id = 88;
for(var i = 0; i < data.length; i++) {
if(data[i].id == id) {
data.splice(i, 1);
break;
}
}
Just iterate through the list, find the matching id, splice, and then break to exit your loop.
There's a new method to do this in ES6/2015 using findIndex and the array spread operator:
const index = data.findIndex(obj => obj.id === id);
const newData = [
...data.slice(0, index),
...data.slice(index + 1)
]
You can turn it into a function for later reuse like this:
function remove(array, key, value) {
const index = array.findIndex(obj => obj[key] === value);
return index >= 0 ? [
...array.slice(0, index),
...array.slice(index + 1)
] : array;
}
This way, you can remove items by different keys using one method (and if there's no object that meets the criteria, you get original array returned):
const newData = remove(data, "id", "88");
const newData2 = remove(data, "name", "You are awesome!");
Or you can put it on your Array.prototype:
Array.prototype.remove = function (key, value) {
const index = this.findIndex(obj => obj[key] === value);
return index >= 0 ? [
...this.slice(0, index),
...this.slice(index + 1)
] : this;
};
And use it this way:
const newData = data.remove("id", "88");
const newData2 = data.remove("name", "You are awesome!");