Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu April 17, 2023 › #HowTo #Javascript

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. #

  1. 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.

  2. 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.

  3. 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.

  4. 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.

save
listen
AI Answer
Write Your Answer
loading
back
View All