
How to remove a property from JavaScript object if exists
To remove a property from a JavaScript object if it exists, you can use the delete operator. The example is given below.
<script> let myObject = { "name": "Red", "Hex": "#ff0000", "RGB": "rgb(255,0,0)" }; if(myObject.hasOwnProperty("RGB")){ delete myObject.RGB; } console.log(myObject); </script>
In the above example, the hasOwnProperty method is used to check if the object has a property "RGB". If it does, the delete operator will remove that property from the object. If it does not, nothing will happen and the object will remain unchanged.
How to remove a property from JavaScript object. #
- Using the delete operator.
<script> let myObject = { "name": "Red", "Hex": "#ff0000", "RGB": "rgb(255,0,0)" }; if(myObject.hasOwnProperty("RGB")){ delete myObject.RGB; } console.log(myObject); </script>
This will remove the "RGB" property from the myObject object, since it exists.
- Using the short-circuiting && operator.
<script> let myObject = { "name": "Red", "Hex": "#ff0000", "RGB": "rgb(255,0,0)" }; myObject.age && delete myObject.age; console.log(myObject); </script>
This will remove the "RGB" property from the myObject object if it exists, using the short-circuiting behavior of the && operator.
- Using a ternary operator.
<script> let myObject = { "name": "Red", "Hex": "#ff0000", "RGB": "rgb(255,0,0)" }; myObject.hasOwnProperty("RGB") ? delete myObject.RGB : null; console.log(myObject); </script>
This will remove the "RGB" property from the myObject object if it exists using a ternary operator.
- Using the in operator.
<script> let myObject = { "name": "Red", "Hex": "#ff0000", "RGB": "rgb(255,0,0)" }; if("RGB" in myObject) { delete myObject.RGB; } console.log(myObject); </script>
This will remove the "RGB" property from the myObject object if it exists, using the in operator.