Open In App

How to remove a key-value pair from JavaScript object?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A JavaScript object is a powerful data structure that combines keys and values. Sometimes, we need to delete a specific key-value from an object. It can be done using the approaches given below.

remove-a-key-value-from-javascript-obj

How to remove a key-value from JavaScript object ?

There are several methods that can be used to remove a key from a JavaScript object:

Using the reduce() and filter() methods

The reduce() and the filter() methods of JavaScript can together be used to remove a key from an JavaScript object.

Syntax of reduce() and filter() method:

Object.keys(object_name).filter(()=>{}).reduce(()=>{});

Example:

The below code example implements the filter and reduce methods together to remove key from an object.

Javascript




let details = {
    name: 'Alex',
    age: 30,
    country: 'Canada'
};
 
console.log('Original Object: ', details);
details = Object.keys(details).filter(objKey =>
    objKey !== 'age').reduce((newObj, key) =>
    {
        newObj[key] = details[key];
        return newObj;
    }, {}
);
console.log(details);


Output

Original Object:  { name: 'Alex', age: 30, country: 'Canada' }
{ name: 'Alex', country: 'Canada' }

Explanation:

  • The original details object contains properties for “name”, “age”, and “country”.
  • The Object.keys(details) method returns an array containing the keys of the details object.
  • The .filter() method filters out the “age” property from the array of keys.
  • The .reduce() method creates a new object (newObj) by iterating over the filtered keys and assigning them to the new object.
  • Finally, the new object without the “age” property is assigned back to the details variable, and it is logged to the console.

Using the delete operator

The delete operator in JavaScript can be used to remove a property (key-value pair) from an object.

Syntax of delete operator:

delete objectName.propertyName;

Example:

The below code removes the ‘age’ key from the object, leaving only the ‘name’ and ‘country’ keys in the object.

Javascript




const details = {
    name: 'Alex',
    age: 30,
    country: 'Canada'
};
 
console.log('Original Object:', details);
delete details.age;
console.log('Object after deleting age key:', details);


Output

Original Object: { name: 'Alex', age: 30, country: 'Canada' }
Object after deleting age key: { name: 'Alex', country: 'Canada' }

Explanation:

  • The original details object contains properties for “name”, “age”, and “country”.
  • The delete operator is used to remove the “age” property from the details object.
  • After deleting the “age” property, the modified details object is logged to the console.

Destructuring with the Rest Operator

Destructuring an object using the rest operator creates a new object without a specified property, keeping the remaining properties from the original object.

Syntax for destructing with rest operator:

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

Example:

The below code uses the destructuring syntax to remove keys from an obect in JavaScript.

Javascript




const details = {
    name: 'Alex',
    age: 30,
    country: 'Canada'
};
console.log('orignal object', details)
// after using destructuring and rest operator
const { age, ...rest } = details;
console.log(rest);


Output

orignal object { name: 'Alex', age: 30, country: 'Canada' }
{ name: 'Alex', country: 'Canada' }

Explanation:

  • The original details object contains properties for “name”, “age”, and “country”.
  • The destructuring assignment { age, ...rest } = details; extracts the “age” property from the details object and assigns it to the age variable. The rest of the properties are collected into a new object called rest.
  • As a result, the rest object contains all properties of the original details object except for the “age” property.
  • The rest object is then logged to the console, showing the object without the “age” property.

Using Object.assign()

Using Object.assign() allows you to create a new object without a specified property by copying all properties except the one you want to remove.

Syntax of object.assign():

const { age, ...rest } = Object.assign({}, details);

Example:

The below code implements the Object.assign() method to remove property from an object.

Javascript




const details = {
    name: 'Alex',
    age: 30,
    country: 'Canada'
};
 
console.log('orignal object', details)
const { age, ...rest } = Object.assign({}, details);
console.log(rest);


Output

orignal object { name: 'Alex', age: 30, country: 'Canada' }
{ name: 'Alex', country: 'Canada' }

Explanation:

  • The Object.assign({}, details) method creates a shallow copy of the details object. This prevents modification of the original details object.
  • Then, object destructuring is used to extract the “age” property from the copied object and assign it to the age variable. The rest of the properties are collected into a new object called rest.
  • As a result, the rest object contains all properties of the original details object except for the “age” property.
  • The rest object is then logged to the console, showing the object without the “age” property.

Using Object.fromEntries() and Object.entries()

The Object.entries() will be used to convert the object into an array of key-value pairs. Then, we use Array.filter() to exclude the key-value pair with the specified key. Finally, we use Object.fromEntries() to convert the filtered array back into an object.

Example:

The below code implements the above methods to remove key from an object in JavaScript.

Javascript




const details = {
    name: 'Alex',
    age: 30,
    country: 'Canada'
};
const { age, ...rest } = Object.fromEntries(
    Object.entries(details).filter(([key]) =>
        key !== 'age'));
console.log(rest);


Output

{ name: 'Alex', country: 'Canada' }

Explanation:

  • Object.entries(details) converts the details object into an array of key-value pairs.
  • .filter(([key]) => key !== 'age') filters out the key-value pairs where the key is not equal to ‘age’, effectively removing the “age” property.
  • Object.fromEntries() converts the filtered array of key-value pairs back into an object.
  • Finally, object destructuring is used to extract the “age” property from the result, which is assigned to the age variable, while the rest of the properties are collected into a new object called rest.
  • The rest object is then logged to the console, showing the object without the “age” property.

Using _.omit method of Underscore.js library to remove a key from object

The underscore.js is an JavaScript library that can be included in an HTML document through its CDN Link and then you are allowed to use its inbuilt functions.

Syntax of _.omit method of Underscore.js library:

objName = _.omit(objName, 'ketToRemove');

Example:

The below code will explain the use of the _.omit() function to remove a key from JavaScript object.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>
        Remove key from JavaScript Object
    </title>
</head>
 
<body>
    <script src=
            integrity=
"sha512-2V49R8ndaagCOnwmj8QnbT1Gz/rie17UouD9Re5WxbzRVUGoftCu5IuqqtAM9+UC3fwfHCSJR1hkzNQh/2wdtg=="
            crossorigin="anonymous"
            referrerpolicy="no-referrer">
        </script>
        <script>
            let details = {
                name: 'Alex',
                age: 30,
                country: 'Canada'
            };
            console.log("Object before removal: ", details);
            details = _.omit(details, 'age');
            console.log("Object after removal: ", details);
        </script>
</body>
 
</html>


Output:

output

Explanation:

  • The Underscore.js library is included in the HTML file using a script tag.
  • Inside the script tag, an object named details is defined with properties for name, age, and country.
  • The _.omit() function from Underscore.js is used to remove the ‘age’ key from the details object.
  • The console.log() statements are used to print the object before and after the removal of the ‘age’ key.

UseCase of Remove a key from JavaScript object

1. JavaScript Object keys() Method

The Object.keys() method in JavaScript is used to retrieve an array of the enumerable property names of an object. It returns an array containing the keys of the object.

2. How to remove object from array of objects using JavaScript ?

There are two approaches to solving this problem which are discussed below: 

3. How to add and remove properties from objects in JavaScript ?

  • For adding any property, one could either use object_name.property_name = value (or) object_name[“property_name”] = value.
  • For deleting any property, one could easily use delete object_name.property_name (or)  delete object_name[“property_name”].



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

Similar Reads