To remove an object from an array in JavaScript where the object's ID matches a specific value, you can use the filter()
method. Here's an example code snippet:
index.tsx236 chars9 lines
In this code, we define an array of objects with id
and name
properties. We then specify the ID value we want to remove with the idToRemove
variable. We then use the filter()
method to create a new array that includes all objects except the one where the id
property matches idToRemove
. Finally, we log the new array to the console to verify that the object with ID 2 has been removed.
Note that the filter()
method creates a new array and does not modify the original array. If you want to remove the object from the original array, you would need to assign the output of filter()
back to the original array like so: arr = arr.filter(obj => obj.id !== idToRemove);
.
gistlibby LogSnag