Removing a property from a JavaScript object
The traditional way to delete an object property from a JavaScript object is to use the delete
command, as seen below.
const driver = {
name: 'Mario',
color: 'red',
kart: 'bike',
};
delete driver.color;
If we try to console.log(driver);
after the delete
command, the result is:
{
kart: "bike",
name: "Mario"
}
Given the driver
object, we can also delete the color
property from this object using the following. The result is the same.
delete driver['color'];
The Immutable Way
The delete
command mutates or changes the initial object. This is not the best approach when it comes to functional programming in JavaScript.
Immutability is an important design pattern of functional programming. Immutability states that something cannot be modified after it is instantiated. If the value of something needs to change, it should be re-created with the new value.
We can remove a property from an object in an immutable way by creating a completely new object that contains copies of all the properties from the old object, except the one property that we want to remove.
const driver = {
name: 'Mario',
color: 'red',
kart: 'bike',
};
const propertyToRemove = 'color';
const newDriver = Object.keys(driver).reduce((newObject, currentKey) => {
if (currentKey !== propertyToRemove) {
newObject[currentKey] = driver[currentKey];
}
return newObject;
}, {});
console.log(newDriver);
By using reduce
on the result of Object.keys(driver)
, we are iterating over all the keys of our driver
object. As long as the current key
of the iteration is not equal to color
, that property is copied to a new object, called newObject
. The object returned will not have the property that contains the key that we want to remove, which is color
.
{
kart: "bike",
name: "Mario"
}
As you can see, the result is the same as the result we obtained earlier with delete driver.color
. However, we have now enforced the principle of immutability, since the driver
object is no longer directly modified after being instantiated.
If you are using React or Angular, the immutable way is the proper way to remove a property from an object in a component's state, or in Redux or ngRx state.
By applying the immutability design pattern, we now have programming code that follows the functional programming paradigm more closely.