How to clone a js object except for one key in javascript?


In computer programming, cloning refers to an object copied by a method or copy factory function often called clone and copy.

The easiest way to clone an object except for one key would be to clone the whole object and then remove the property that is not required. Cloning, however, can be of 2 types −

  • Deep Clone

  • Shallow Clone

Shallow Clone

The shallow clone copies as little as possible. For example, a shallow copy of a collection might be a copy of the collection’s structure, not its elements. With a shallow copy, two collections now share individual elements.

Example

Let us see an example −

<!DOCTYPE html>
<html>
<head>
   <title>Example</title>
</head>
<body>
   <script>
      let innerObj = {
         a: 'b',
         c: 'd'
      }
      let obj = {
         x: "test",
         y: innerObj
      }
      // Create a shallow copy.
      let copyObj = Object.assign({}, obj);
     
      // Both copyObj and obj's prop y now refers to the same innerObj. Any changes to this will be reflected.
      innerObj.a = "test";
      document.write("Original Object: ");
      document.write(JSON.stringify(obj),"<br>");
      document.write("Copy: ");
      document.write(JSON.stringify(copyObj));
   </script>
</body>
</html>

Note − that shallow copies do not make clones recursively. It just does it at the top level.

Deep Clone

Deep clone duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection cloned.

Example 1

Following is an example of the deep clone.

<!DOCTYPE html>
<html>
<head>
   <title>Example</title>
</head>
<body>
   <script>
      let innerObj = {
         a: 'b',
         c: 'd'
      }
      let obj = {
         x: "test",
         y: innerObj
      }
      // Create a deep copy.
      let copyObj = JSON.parse(JSON.stringify(obj));
      innerObj.a = "test";
      document.write("Original Object: ");
      document.write(JSON.stringify(obj), "<br>");
      document.write("Copy: ");
      document.write(JSON.stringify(copyObj));
   </script>
</body>
</html>

Once you get a copy using either of these methods, you can remove the property you don't require using the delete keyword. For example,

Example 2

<!DOCTYPE html>
<html>
<head>
   <title>Example</title>
</head>
<body>
   <script>
      let original = { 
         x: 'test', 
         y: { 
            a: 'test', 
            c: 'd' 
         } 
      }
      let copy = JSON.parse(JSON.stringify(original))
      delete copy['x']
      document.write(JSON.stringify(copy), "<br>")
      document.write(JSON.stringify(original))
   </script>
</body>
</html>

Let us see a few more examples −

Example 3

In the following example, we are creating a clone function named objectExceptOne which will print all the object values and keys except one.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Clone javascript object except One Key</title>
</head>
<body>
   <script>
      // create a function and pass the parameter first is your object and second is that need to be removed.
      function objectExceptOne(obj, keys) {

         //create an empty object named target
         var target = {};

         //itrating the loop and storing the value in the target object
         for (var i in obj) {

            if (keys.indexOf(i) >= 0) continue;
            if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
            target[i] = obj[i];
         }
         return target;
      }
      var x = { 
         a: "aman", 
         b: "tutorialspoint", 
         c: "Easy To Learn", 
         d: "Technical Writer" 
      };

      var a = x.a;
      var y = objectExceptOne(x, ["a"]);
      document.write(JSON.stringify(y)); // printing the remaining value;
   </script>
</body>
</html>

Example 4

In the following example, we are using Object.assign() to exclude one key from the object.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Document</title>
</head>
<body>
   <script>
      var clone = Object.assign({}, { a: "aman", b: "tutorialspoint", c: "Easy To Learn", d: "Technical Writer" });
      delete clone.b;
      document.write(JSON.stringify(clone));
   </script>
</body>
</html>

Example 5

In the following example, we are using ESnext one−liner and removing the a and c keys.

<!DOCTYPE html>
<html lang="en">
<body>
   <script>
      var obj = {
         a: "aman",
         b: "tutorialspoint",
         c: "Easy To Learn",
         d: "Technical Writer",
      };
      const clone = (({ a, c, ...o }) => o)(obj); // remove a and c
      document.write(JSON.stringify(clone));
   </script>
</body>
</html>

Example 6

In the following example, we are using _.omit() which accepts two parameters first one is an object and the second one is the keys that you want to filter out from on the Object.

<!DOCTYPE html>
<html>
<head>
   <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" ></script>
</head>
<body>
   <script type="text/javascript">
      var comInfo = {
         Company: "tutorialspoint",
         Address: "Hyderabad",
         Contact: "+915678889902",
      };
      //Removing company and address
      document.write(JSON.stringify(_.omit(comInfo, "Company", "Address")));
   </script>
</body>
</html>

Example 7

In the following example, we are writing a simple helper function for clone, like javascrit have underscore.js library _.omit() function.

<!DOCTYPE html>
<html lang="en">
<body>
   <script>
      function omit(obj, omitKey) {
         return Object.keys(obj).reduce((result, key) => {
            if (key !== omitKey) {
               result[key] = obj[key];
            }
            return result;
            }, {});
         }
         document.write(JSON.stringify(omit({
         Company: "tutorialspoint",
         Address: "Hyderabad",
         Contact: "+915678889902",
      },
      "Contact"
      )));
   </script>
</body>
</html>

Updated on: 19-Dec-2022

979 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements