Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript find and remove object in array based on key value

I have been trying several approaches on how to find an object in an array, where ID = var, and if found, remove the object from the array and return the new array of objects.

Data:

[
    {"id":"88","name":"Lets go testing"},
    {"id":"99","name":"Have fun boys and girls"},
    {"id":"108","name":"You are awesome!"}
]

I'm able to search the array using jQuery $grep;

var id = 88;

var result = $.grep(data, function(e){
     return e.id == id;
});

But how can I delete the entire object when id == 88, and return data like the following?

Data:

[
    {"id":"99", "name":"Have fun boys and girls"},
    {"id":"108", "name":"You are awesome!"}
]
like image 909
Tom Avatar asked Oct 03 '22 02:10

Tom


People also ask

How do I remove an object by key from an array of objects?

To remove a property from all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.

How can I remove a key value pair to a JavaScript object?

With pure JavaScript, use: delete thisIsObject['Cow'];


1 Answers

Here is a solution if you are not using jQuery:

myArray = myArray.filter(function( obj ) {
  return obj.id !== id;
});
like image 263
Adam Boostani Avatar answered Oct 04 '22 15:10

Adam Boostani