How to use Object.fromEntries() and Object.entries() In Javascript
The Object.entries() will be used to convert the object into an array of key-value pairs. Then, we use Array.filter() to exclude the key-value pair with the specified key. Finally, we use Object.fromEntries() to convert the filtered array back into an object.
Example:
The below code implements the above methods to remove key from an object in JavaScript.
const details = {
name: 'Alex',
age: 30,
country: 'Canada'
};
const { age, ...rest } = Object.fromEntries(
Object.entries(details).filter(([key]) =>
key !== 'age'));
console.log(rest);
Output
{ name: 'Alex', country: 'Canada' }
Explanation:
Object.entries(details)
converts thedetails
object into an array of key-value pairs..filter(([key]) => key !== 'age')
filters out the key-value pairs where the key is not equal to ‘age’, effectively removing the “age” property.Object.fromEntries()
converts the filtered array of key-value pairs back into an object.- Finally, object destructuring is used to extract the “age” property from the result, which is assigned to the
age
variable, while the rest of the properties are collected into a new object calledrest
. - The
rest
object is then logged to the console, showing the object without the “age” property.
How to remove a key-value pair from JavaScript object?
JavaScript object is a powerful data structure that combines keys and values. Sometimes, we need to delete a specific key-value from an object. It can be done using the approaches given below.
There are several methods that can be used to remove a key from a JavaScript object:
Table of Content
- Using the reduce() and filter() methods
- Using the delete operator
- Destructuring with the Rest Operator
- Using Object.assign()
- Using Object.fromEntries() and Object.entries()
- Using _.omit method of Underscore.js library
- UseCase of Remove a key from JavaScript object