Open In App

JavaScript | Remove a JSON attribute

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:



Syntax:

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

Parameters:



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.




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.




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"}}


Article Tags :