A JSON object is commonly represented as a JavaScript object when working with JSON data in JavaScript. You can remove an attribute (property) from an object using the delete operator.
[Approach 1]: Using the delete Operator with Bracket Notation
Bracket notation is useful when the property name is stored in a variable.
- Create a JavaScript object containing the properties.
- Store the property name to remove in a variable.
- Use delete with bracket notation to remove the property.
Example: The following example removes a property using a variable key.
let myObj = {
prop_1: {
prop_11: "value_11",
prop_12: "value_12"
}
};
function removeJsonAttr() {
const key = "prop_12";
delete myObj.prop_1[key];
console.log(JSON.stringify(myObj));
}
removeJsonAttr();
Output
{"prop_1":{"prop_11":"value_11"}}
[Approach 2]: Using the delete Operator with Dot Notation
Dot notation can be used when the property name is known directly.
- Access the required object property.
- Use the delete operator with dot notation.
- The specified property is removed from the object.
Example: The following example removes a property using its known name.
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"}}