Delete a Key-Value Pair from an Object in JavaScript?
Question: How to Delete a Key-Value Pair from an Object in an Array by Value in JavaScript?
I have an array of objects in JavaScript, and I need to delete a specific key-value pair based on the value. Here is an example of what my data looks like:
I want to remove the role
key-value pair where the role is 'admin'
. After removing it, the array should look like this:
How can I achieve this in JavaScript?
Solution: Deleting a Key-Value Pair Based on Value in an Array of Objects
In JavaScript, you can loop through the array of objects and use the delete
operator to remove a key-value pair based on a condition.
Step-by-Step Approach:
- Loop through the array using
forEach()
. - Inside the loop, check if the value matches the condition (e.g.,
role === 'admin'
). - Use the
delete
operator to remove the key from the object.
Here’s how you can do it:
Output:
Explanation:
- The
forEach()
method loops through each object in the array. - The
if
condition checks if therole
value is'admin'
. - The
delete
operator is then used to remove therole
key from the object if the condition is met.
Additional Methods:
You could also use other approaches, like map()
, if you need to return a new array rather than modifying the existing one:
This method uses object destructuring to remove the key and returns a new array.
Conclusion:
When working with arrays of objects, the delete
operator or destructuring techniques provide a flexible way to remove key-value pairs based on specific conditions. Choose the approach that best suits your needs depending on whether you want to mutate the original array or create a new one.