How to use the reduce() and filter() methods In Javascript
The reduce() and the filter() methods of JavaScript can together be used to remove a key from an JavaScript object.
Syntax of reduce() and filter() method:
Object.keys(object_name).filter(()=>{}).reduce(()=>{});
Example:
The below code example implements the filter and reduce methods together to remove key from an object.
let details = {
name: 'Alex',
age: 30,
country: 'Canada'
};
console.log('Original Object: ', details);
details = Object.keys(details).filter(objKey =>
objKey !== 'age').reduce((newObj, key) =>
{
newObj[key] = details[key];
return newObj;
}, {}
);
console.log(details);
Output
Original Object: { name: 'Alex', age: 30, country: 'Canada' } { name: 'Alex', country: 'Canada' }
Explanation:
- The original
details
object contains properties for “name”, “age”, and “country”. - The
Object.keys(details)
method returns an array containing the keys of thedetails
object. - The
.filter()
method filters out the “age” property from the array of keys. - The
.reduce()
method creates a new object (newObj
) by iterating over the filtered keys and assigning them to the new object. - Finally, the new object without the “age” property is assigned back to the
details
variable, and it is logged to the console.
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
Contact Us