Open In App

JavaScript | Remove a JSON attribute

Last Updated : 11 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to remove a JSON attribute from the JSON object. To do this, there are few of the mostly used techniques discussed. First delete property needs to be discussed.

Delete property to Remove a JSON Attribute

This keyword deletes a property from an object:

  • This keyword deletes both the value of the property and the property itself.
  • After deletion, the property is not available for use before it is added back again.
  • This operator is created to be used on object properties, not on variables or functions.
  • This operator should not be used on predefined JavaScript object properties. It can crash your application.

Syntax:

delete object.property or
delete object['property']

Parameters:

  • object: It specifies the name of an object, or an expression evaluating to an object.
  • property: It specifies the property to delete.

Return value: It returns true for all cases and returns false when the property is an own non-configurable property.

Example 1: This example deletes the prop_12 from the myObj object via variable key by using delete property.

Javascript




let myObj = {
    'prop_1': {
        'prop_11': 'value_11',
        'prop_12': 'value_12'
    }
};
 
function removeJsonAttr() {
    let key = "prop_12";
    delete myObj.prop_1[key];
     
    console.log(JSON.stringify(myObj));
}
 
removeJsonAttr();


Output

{"prop_1":{"prop_11":"value_11"}}

Example 2: This example deletes the prop_11 from the myObj object by using delete property.

Javascript




let myObj = {
    'prop_1': {
        'prop_11': 'value_11',
        'prop_12': 'value_12'
    }
};
 
function removeJsonAttr() {
    delete myObj.prop_1.prop_11;
     
    console.log(JSON.stringify(myObj));
}
 
removeJsonAttr();


Output

{"prop_1":{"prop_12":"value_12"}}



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads