How to use Destructuring and Object.assign In Javascript
This method involves using object destructuring to exclude specific keys and then reassembling the remaining keys into a new object using Object.assign.
Syntax:
const { keyToRemove, ...rest } = object;
const newObject = Object.assign({}, rest);
Example: This example demonstrates how to use destructuring and Object.assign to remove a key-value pair from an object.
let myObj = {
Name: "Raghav",
Age: 30,
Sex: "Male",
Work: "Web Developer",
YearsOfExperience: 6,
Organisation: "w3wiki",
Address: "address--address some value"
};
// Function to delete a key using destructuring and Object.assign
function removeKey(obj, keyToRemove) {
const { [keyToRemove]: _, ...rest } = obj;
return Object.assign({}, rest);
}
let updatedObj = removeKey(myObj, "Address");
console.log("After removal:");
console.log(updatedObj);
Output
After removal: { Name: 'Raghav', Age: 30, Sex: 'Male', Work: 'Web Developer', YearsOfExperience: 6, Organisation: 'w3wiki' }
How to Remove an Entry by Key in JavaScript Object?
In JavaScript, objects store data in the form of key-value pairs where the key may be any property of the object. In this article let us see how to remove key-value pairs a by given key in the object.
Table of Content
- Using the delete operator
- Using the filter() method
- Using Destructuring and Object.assign