Skip to content

Remove property from object JavaScript

  • by

Use the delete operator to Remove the property from an object in JavaScript. The delete operator deletes a property from an object. It has no effect on variables or functions.

delete object.property;

The Object property can be accessed either using the dot notation or the square brackets notation.

delete object[‘property’]

Remove property from object JavaScript example

A simple example code used the delete keyword to remove the prop2 property from myObj. Finally, we log the updated object to the console and confirm that the prop2 property has been removed.

<!DOCTYPE html>
<html>

<body>
  <script >
    let myObj = {
      prop1: "value1",
      prop2: "value2",
      prop3: "value3"
      };

      // Removing property 'prop2'
      delete myObj.prop2;

    console.log(myObj);
  </script>
</body>
</html>

Output:

Remove property from object JavaScript

Delete property and its values in all the object

You could use a recursive algorithm :

function del_entries(key, obj) {
  if (obj.hasOwnProperty(key)) {
    delete obj[key];
  }

  // Or with Object.hasOwn, not fully supported by old browsers but more up to date
 /*
 if (Object.hasOwn(obj, key)) {
     delete obj[key]
 }
 */
  
  Object.values(obj).forEach(o=> del_entries(key, o))
}


const MyGraph = {
    a: { b: 5, c: 2 },
    b: { a: 5, c: 7, d: 8 },
    c: { a: 2, b: 7, d: 4, e: 8 },
};

del_entries("a", MyGraph);

console.log(MyGraph)

Output:

{
  "b": {
    "c": 7,
    "d": 8
  },
  "c": {
    "b": 7,
    "d": 4,
    "e": 8
  }
}

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading