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:

const users = [
{ id: 1, name: 'John', role: 'admin' },
{ id: 2, name: 'Jane', role: 'editor' },
{ id: 3, name: 'Jack', role: 'admin' }
];

I want to remove the role key-value pair where the role is 'admin'. After removing it, the array should look like this:

[
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane', role: 'editor' },
{ id: 3, name: 'Jack' }
]

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:

  1. Loop through the array using forEach().
  2. Inside the loop, check if the value matches the condition (e.g., role === 'admin').
  3. Use the delete operator to remove the key from the object.

Here’s how you can do it:

const users = [
{ id: 1, name: 'John', role: 'admin' },
{ id: 2, name: 'Jane', role: 'editor' },
{ id: 3, name: 'Jack', role: 'admin' }
];

users.forEach(user => {
if (user.role === 'admin') {
delete user.role; // Remove the key-value pair
}
});

console.log(users);

 

Output:

[
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane', role: 'editor' },
{ id: 3, name: 'Jack' }
]

Explanation:

  • The forEach() method loops through each object in the array.
  • The if condition checks if the role value is 'admin'.
  • The delete operator is then used to remove the role 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:

const updatedUsers = users.map(user => {
if (user.role === 'admin') {
const { role, ...rest } = user; // Destructure to remove 'role'
return rest;
}
return user;
});

console.log(updatedUsers);

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.

Related Blog

Sign up for our newsletter to stay up to
date with tech news!