When dealing with objects, sometimes we wish to exclude certain properties from that object. JavaScript gives us an easy to exclude the properties we want to exclude and putting the rest into a new object.
Example
Suppose we have an object called employee
and we want to remove the following properties: id
, positionId
, and departmentId
. We accomplish this by using destructuring and extracting the properties we want to exclude and then use the rest operator in order to take the rest of the object properties and place them into a new object called employeeObj
.
const employee = {
id: 123,
firstName: 'Ahmad',
lastName: 'Hussein',
positionId: 45,
position: 'Product Manager',
departmentId: 34,
department: 'Engineering'
}
const {
id,
positionId,
departmentId,
...employeeObj
} = employee
console.log(employeeObj);
/*{
department: "Engineering",
firstName: "Ahmad",
lastName: "Hussein",
position: "Product Manager"
}*/