Destructuring with the Rest Operator
Destructuring an object using the rest operator creates a new object without a specified property, keeping the remaining properties from the original object.
Syntax for destructing with rest operator:
const { propertyToRemove, ...rest } = objectName;
Example:
The below code uses the destructuring syntax to remove keys from an obect in JavaScript.
const details = {
name: 'Alex',
age: 30,
country: 'Canada'
};
console.log('orignal object', details)
// after using destructuring and rest operator
const { age, ...rest } = details;
console.log(rest);
Output
orignal object { name: 'Alex', age: 30, country: 'Canada' } { name: 'Alex', country: 'Canada' }
Explanation:
- The original
details
object contains properties for “name”, “age”, and “country”. - The destructuring assignment
{ age, ...rest } = details;
extracts the “age” property from thedetails
object and assigns it to theage
variable. The rest of the properties are collected into a new object calledrest
. - As a result, the
rest
object contains all properties of the originaldetails
object except for the “age” property. - 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
Contact Us