I have found myself many many times in a situation where I wanted to delete a property from an object in JavaScript.
In this article, I take you through multiple ways to achieve this. It's worth mentioning many of these techniques are exactly applicable even when you use a framework or at least you'll use a very similar approach there too.
Before we move on, remember you can build your websites, landing pages, APIs, and more, with or without coding on DoTenX for free. Make sure to check it out and use it to your advantage. DoTenX is open-source and you can find the repository here: github.com/dotenx/dotenx.
Let's get started.
1. The first way is to just use the delete
operator. It's pretty simple and straightforward:
let myObject = { x: 1, property: 2};
delete myObject.property;
2. Another way to remove a property is to use the Object.assign()
method which creates a new object without the property you wanted to remove.
const newObject = Object.assign({}, myObject);
delete newObject.property;
This method is commonly used when you want to maintain immutability of the original object and not change it. This approach is much more preferred to just using the delete
operator.
3. You can also use the Object.entries()
method to remove a property from an object. This method returns an array of arrays containing the key-value pairs of an object. You can then use the filter()
method to exclude the key-value pair that you want to remove.
const newObject = Object.fromEntries(
Object.entries(myObject).filter(([key]) => key !== 'property')
);
It's better to use this approach if you also want to do some extra processing on the object.
4. Another way of deleting a property is using the spread operator ...
to create a new object and exclude the property that you want to remove. I've found this approach especially common among React developers.
const { property, ...newObject } = myObject;
5. For removing deeply nested properties, you can use the fantastic lodash
library's method _.unset(object, '
path.to.property
')
import _ from 'lodash';
_.unset(myObject, 'path.to.property');
6. Finally, if the property is not known until runtime, you can use object[property name] to refer to the property and delete it:
const property = 'aProperty'; // value is set at runtime
delete myObject[property]