To remove a property from an object you can use a combination of object destructuring and rest
parameters in JavaScript. It is one of the performant ways you could remove a property from an object.
TL;DR
// a simple object
const John = { name: "John", age: 23 };
// remove age from object
const { age, ...allOtherPropeties } = John;
// age property is removed
console.log(allOtherPropeties); // {name: "John"} 😃
For example, let's say i have an object with properties like name
, age
, salary
and isAdult
properties like this,
// a simple object
const John = {
name: "John Doe",
age: 23,
salary: 45000,
isAdult: true,
};
Now let's remove the salary
and isAdult
properties using the object destructuring and rest
parameter (...
). We can put the properties we want to remove inside the curly braces, for example, the properties salary
and isAdult
properties can be put inside the curly braces like this,
// a simple object
const John = {
name: "John Doe",
age: 23,
salary: 45000,
isAdult: true,
};
// remove salary and isAdult properites
const { salary, isAdult } = John;
What the above line essentially means is that you are specifically picking or destructuring 2 properties salary
and isAdult
from the object John
.
Now we can add one expression called allOtherPropeties
prefixed by three-dot or rest parameter (...)
inside the curly braces but after the salary
and isAdult
properties like this,
// a simple object
const John = {
name: "John Doe",
age: 23,
salary: 45000,
isAdult: true,
};
// remove salary and isAdult properties
const { salary, isAdult, ...allOtherPropeties } = John;
The above statement will pick or destructure salary
and isAdult
properties from object John
and put all the other properties except salary
and isAdult
into the allOtherPropeties
variable. So in the end, the allOtherPropeties
variable will only have name
and age
properties present in them.
// a simple object
const John = {
name: "John Doe",
age: 23,
salary: 45000,
isAdult: true,
};
// remove salary and isAdult properties
const { salary, isAdult, ...allOtherPropeties } = John;
// log the contents inside the allOtherProperties
console.log(allOtherPropeties);
/*
OUTPUT:
{
name: "John Doe",
age: 23
}
*/
See the above code live in JSBin.
This is a much more performant way of eliminating or removing properties from an object. You can also use the delete
operator to delete properties from an object. Using the delete
operator has some performance problems with the Chrome V8 engine.
That's all! 😃