How to use Object.assign() In Javascript
Using Object.assign() allows you to create a new object without a specified property by copying all properties except the one you want to remove.
Syntax of object.assign():
const { age, ...rest } = Object.assign({}, details);
Example:
The below code implements the Object.assign() method to remove property from an object.
const details = {
name: 'Alex',
age: 30,
country: 'Canada'
};
console.log('orignal object', details)
const { age, ...rest } = Object.assign({}, details);
console.log(rest);
Output
orignal object { name: 'Alex', age: 30, country: 'Canada' } { name: 'Alex', country: 'Canada' }
Explanation:
- The
Object.assign({}, details)
method creates a shallow copy of thedetails
object. This prevents modification of the originaldetails
object. - Then, object destructuring is used to extract the āageā property from the copied object and assign it to the
age
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