How to Remove a Key from an Object in JavaScript

How-to-remove-a-key-from-an-object-in-javascript
How-to-remove-a-key-from-an-object-in-javascript

Here are the two simple ways to delete a key from an object in javascript.

Removing a key from an object with delete operator

You can use the delete operator to remove a key from an object in javascript. You just have to use the key with the delete operator as delete key. Check the example below.

The output of the above code will be:

“John”

undefined

You can also use the other syntax with the delete operator. See the example given below.

The above code will do the same thing and the output will be the same as above.

Using undefined to remove a key from an object

You can also set the key of an object to undefined which will also remove the key from that object. Chech the example.

output: “John”¬†

undefined

Using the other syntax for removing the key from the object.

The output will be the same as above. This second method also deletes a key from an object. But, what about the nested objects? How you can remove a key from the nested object? Well, You can use the above methods to remove a key from the nested object. Here is an example.

The above code will generate the following output.

97134567891 

undefined

You can look into the delete operator in detail on mozila developer guide.

Conclusion

You can use the delete operator to remove a key from an object or use the other method which sets the key to undefined. Both these methods remove a key from an object in javascript.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here