Skip to content
Related Articles

Related Articles

Improve Article

How to remove the key-value pairs corresponding to the given keys from an object using JavaScript ?

  • Difficulty Level : Medium
  • Last Updated : 22 Jul, 2021

In JavaScript objects store data in the form of key-value pairs where the key may be any property of the object. In this article let us see how to remove key-value pairs corresponding to a given key in the object.

Using delete operator. When only a single key is to be removed we can directly use the delete operator specifying the key in an object.
 

Syntax:

 

delete(object_name.key_name);
/* or */
delete(object_name[key_name]);

 



Example:

 

HTML




<script>
      var myObj = {
        Name: "Raghav",
        Age: 30,
        Sex: "Male",
        Work: "Web Developer",
        YearsOfExperience: 6,
        Organisation: "GeeksforGeeks",
        Address: "address--address some value"
      };
  
      console.log("After removal: ");
      // Deleting address key
      delete (myObj.Address); // Or delete(myObj[Address]);
      console.log(myObj);
</script>    

Output:

"After removal: "
[object Object] {
  Age: 30,
  Name: "Raghav",
  Organisation: "GeeksforGeeks",
  Sex: "Male",
  Work: "Web Developer",
  YearsOfExperience: 6
}

When multiple keys are to be removed then the keys can be stored in an array and can be passed to a function that uses a loop to delete the required keys in the array.
 

Syntax:

 

function function_name(object_name, array_of_keys) {
    { Iterate through the array using loop. }
    return object_name;
}

 

Example 2:

 

HTML




<script>
    // Function to delete the keys given in the array
    function DeleteKeys(myObj, array) {
      for (let index = 0; index < array.length; index++) {
          delete myObj[array[index]];
      }
      return myObj;
    }
  
    // Declaring the object
    var myObj = {
      Name: "Raghav",
      Age: 30,
      Sex: "Male",
      Work: "Web Developer",
      YearsOfExperience: 6,
      Organisation: "Geeks For Geeks",
      Address: "address--address some value"
    };
  
    // Adding the keys to be deleted in the array
    var array = 
    ["Work", "Address", "Organisation", "YearsOfExperience"];
    var finalobj = DeleteKeys(myObj, array);
    console.log("After removal: ");
    console.log(finalobj);
</script>

Output:

"After removal: "
[object Object] {
  Age: 30,
  Name: "Raghav",
  Sex: "Male"
}



My Personal Notes arrow_drop_up
Recommended Articles
Page :