How to shallow copy the objects in JavaScript?


In this article we are going to discuss how to perform shallow copy on JavaScript objects.

If the source value is the reference to an object, then it will only copy the reference value into the target value.

When the source properties are copied without reference and there exists a source property whose value is an object and is copied as a reference.

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into the objects found in the original.

Using the _.extend() method

Underscore.js are a library of JavaScript and has a method called _.extend() to shallow copy the objects of JavaScript. This method copies all the properties in the source object over the destination object. And return the destination object.

Note − it does not copy the duplication.

Syntax

Following is the syntax of the _.extend() method 

_.extend(object*);

This method accepts only one argument as an object and shallow copy. And we provide as many objects as we want.

Example: 1

In the following example we are passing more than two objects and performing a shallow copy.

<html>
<body>
   <script type="text/javascript"src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"
></script>
</head>
<body>
   <script>
      var res = JSON.stringify(_.extend(
      {name: 'Rahul', designation: "Technical developer"},
      {age: 24},
      {salary: 1000000}));
      document.write((res));
   </script>
</body>
</html>

Example 2

In the following example, we are doing the same that we have done in the above example but here we are passing one extra value with the same key but a different value. But it gives the out of last key-value pairs not first.

<html>
<body>
   <script type="text/javascript"src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
</head>
<body>
   <script>
      var res = JSON.stringify(_.extend(
      {name: 'Rahul', designation: "Technical developer"},
      {age: 24},
      {name: 'Aman', designation: "Software developer"},
      {salary: 1000000}));
      document.write((res));
   </script>
</body>
</html>

Example: 3

In the following example, we are using another method Object.assign() to copy from source to target. Following is the syntax of the Object.assign() method −

Object.assign({}, person);

This accepts two parameters first is the target object and the second is the source. Here the target is empty ({}) and the source is an object.

<html>
<body>
   <script type="text/javascript"src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
</head>
<body>
   <script>
      let person = {
         firstName: 'Jkshon',
         lastName: 'Doe',
         address: {
            street: 'North 1st street',
            city: 'San Jose',
            state: 'CA',
            country: 'USA'
         }
      };
      let copiedPerson = Object.assign({}, person);
      copiedPerson.firstName = 'Jane';
      copiedPerson.address.street = 'Amphitheatre Parkway';
      copiedPerson.address.city = 'Mountain View';
      document.write(JSON.stringify(copiedPerson));
   </script>
</body>
</html>

Example 4: Using the spread Operator

In the following example we are trying to perform a shallow copy using a spread operator −

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>Shallow copy using spread operator</title>
   <div id="shallow"></div>
</head>
<body>
   <script type="text/javascript">
      let obj = {
         name: "Alice",
         age: {
            newAge: 22,
         },
         role: "Full stack developer",
         };
         let shallowCopy = {
            ...obj,
         };
         shallowCopy.age.newAge = 21;
         document.write(JSON.stringify(obj));
         document.write(JSON.stringify(shallowCopy));
   </script>
</body>
</html>

Example 5: Using the assignment operator

We can also perform shallow copy using the assignment operator. Following is an example for that −

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>Shallow copy using assingment operator</title>
   <div id="shallow"></div>
</head>
<body>
   <script type="text/javascript">
      let obj = {
         name: "Alice",
         age: 21,
         role: "Full stack developer",
      };
      let shallowCopy = obj;
      shallowCopy.age = 22;
      document.write(JSON.stringify(obj));
      document.writr(JSON.stringify(shallowCopy));
   </script>
</body>
</html>

Updated on: 06-Dec-2022

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements