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.

JavaScript
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

Similar Reads

Using the delete operator

When only a single key is to be removed we can directly use the delete operator specifying the key in an object....

Using the filter() method

The JavaScript Array filter() Method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method....

Using Destructuring and Object.assign

This method involves using object destructuring to exclude specific keys and then reassembling the remaining keys into a new object using Object.assign....