6 Ways to Delete a Property In JavaScript You Must Know

Sam - Jan 12 '23 - - Dev Community

You might ask yourself how can I remove a property from a JavaScript object? I've found myself in this situation countless times.

In this article, I take you through 6 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: 'something'};
delete myObject.property;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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')
);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

6. Finally, if the property is not known until runtime, you can use the object[property name] to delete it.

const property = 'aProperty'; // value is set at runtime
delete myObject[property]
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .