Open In App

How to Remove Element from JSON Object in JavaScript ?

In JavaScript, removing elements from a JSON object is important for modifying data structures dynamically. This object manipulation can help us to create dynamic web pages.

The approaches to accomplish this task are listed and discussed below:

Using delete Keyword

In this approach, we are using the delete keyword to directly remove a specific key from the JSON object. After deletion, the updated object no longer contains the deleted key, as seen when logging the object to the console.

Syntax:

delete objectName.propertyName;

Example: The below example uses the delete keyword to remove an element from JSON object in Javascript.

let jObj = {
    "company": "GeeksforGeeks",
    "courses": ["DSA", "Web Tech", 
        "Placement_Preparation", "DDA"]
};
delete jObj.courses;
console.log(jObj);

Output
{ company: 'GeeksforGeeks' }

Using filter Method

In this approach, we are using the filter method with Object.entries to create an array of key-value pairs, then filtering out the key based on a condition. Finally, we use Object.fromEntries to convert the filtered array back into a JSON object.

Syntax:

let updatedObject = Object.fromEntries(
Object.entries(originalObject).filter(
([key, value]) =>
/* condition to keep or remove key */)
);

Example: The below example uses the filter Method to remove an element from JSON object in JavaScript.

let jObj = {
    "company": "GeeksforGeeks",
    "courses": ["DSA", "Web Tech", 
        "Placement_Preparation", "DDA"]
};
jObj = Object.fromEntries(
    Object.entries(jObj).
        filter(([key, value]) => 
            key !== "courses")
);
console.log(jObj);

Output
{ company: 'GeeksforGeeks' }

Using Destructuring

In this approach using destructuring, we extract the key from the JSON object into a variable courses while collecting the rest of the object into res. Printing res shows the JSON object jArr without the "courses" key.

Syntax:

const { propertyToRemove, ...rest } = objectName;

Example: The below example uses the Destructuring to remove an element from json object in JavaScript.

let jArr = {
    "company": "GeeksforGeeks",
    "courses": ["DSA", "Web Tech", 
        "Placement_Preparation", "DDA"]
};
let { courses, ...res } = jArr;
console.log(res); 

Output
{ company: 'GeeksforGeeks' }
Article Tags :