I recently got asked how to remove a property from an object in JavaScript.
Here is an example object::
let linuxDistros = {
"Ubuntu": "20.04",
"CentOS": "8",
"Debain": "10"
};
Let’s say that we wanted to remove the CentOS
properly. Here are a couple of ways on how to do that.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
In order to remove a property from an object in JavaScript, you can use the delete
followed by your Object and the property that you want to remove.
If we take the object from the question:
let linuxDistros = {
"Ubuntu": "20.04",
"CentOS": "8",
"Debain": "10"
};
We can remove the CentOS
property with the following:
delete linuxDistros.CentOS;
Here is a quick demo on how this would work:
Here is an alternative syntax as well:
delete linuxDistros['CentOS'];
If you want to learn more about how to make changes to the DOM with JavaScript make sure to check out the following tutorial:
https://www.digitalocean.com/community/tutorials/how-to-make-changes-to-the-dom
Hope that this helps! Bobby
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.
Note: The delete operator should not be used on predefined JavaScript object properties. It can crash your application.