Different techniques for copying objects in JavaScript


In JavaScript, objects are the collection of a key value pairs. The properties of the object are the keys and is denoted with a string. The value of the key is the value of the property of the given object.

Types/Techniques of object copying

There are 2 types of copying objects in any language namely: deep copy, and shallow copy.

Shallow Copy

In this technique an object is copied as little as possible. For suppose if you copy a collection using this technique the structure of the collection is copied to the destination, not the elements.

Example

Following is an example of shallow copy −

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" console.log(obj) console.log(copyObj)

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

Deep copy

In deep copy the object is completely duplicated. A deep copy of a collection is two collections with all of the elements in the original collection cloned.

Example

Following is an example of deep copy −

let innerObj = { a: 'b', c: 'd' } let obj = { x: "test", y: innerObj } // Create a deep copy. let copyObj = JSON.parse(JSON.stringify(obj)) // Both copyObj and obj's prop y now refers to the same innerObj. Any changes to this will be reflected. innerObj.a = "test" console.log(obj) console.log(copyObj)

Other ways of copying an object

In JavaScript, the objects can be copied to another by many ways in which some of them are discussed below.

Using spread operator(…)

The spread operator in JavaScript is used to copy the values of the original given object to a new object. This operator is represented by three dots(…).

Example

This example demonstrates how spread operator is used to copy objects in JavaScript −

var employee = { emp_name: "Abdul Rawoof", company: "Tutorials Point", salary: 18000, job: "Software Engineer-Intern" } console.log("The original object employee is:", employee) var cpyEmployee = {...employee} console.log("The copied object cpyEmployee is:",cpyEmployee);

If the object has nested objects, then some additional lines should be written when spread operator is used.

Using assign() function

This function is used to copy the original object into a new object. The difference in this and the spread operator is when nested objects are present and if assign() is used to copy the object, then the nested object will not change and the other variables of the object can be changed.

There are two parameters to the assign() function. The first parameter is curly braces {} which is used to ensure that the new object will not mutate the original object. The second parameter is the name of the original object which is to be copied into new object.

Syntax

Following is the syntax for the assign() function.

Object.assign({},originalObjectName)

Example

This example demonstrates the usage of assign() to copy objects into a new object −

var employee = { emp_name: "Abdul Rawoof", company: "Tutorials Point", salary: 18000, job: "Software Engineer-Intern" } console.log("The original object employee is:", employee) var cpyEmployee = Object.assign({},employee) console.log("The copied object cpyEmployee is:",cpyEmployee); cpyEmployee.emp_name="Jason" cpyEmployee.job="Content writer-Intern" console.log("The copied object with some different name and role is:",cpyEmployee)

In the above example the original object is copied into the new object and then the properties of the objects are changed. So, from this it is concluded that we can update the values of the properties of the object after copying it from the original object.

When these are copied by using the assign() function the original value and the new copied value will have the same reference. So, change in one can alter the change in the other accordingly.

Using JSON

This is used to copy the original object in a quick and easy way into a new object. This function can be used to copy when the given input is numbers, strings and Object literals.

In this way, two methods have to be used to copy the object, they are parse() and stringify() functions. Parse() function will parse the string to JavaScript object. By doing this the two objects will have their individual memory.

Syntax

The syntax for the json() method is given below.

JSON.parse(JSON.stringify(originalObjectName))

Example

This example demonstrates the usage of parse() and stringify() to copy objects −

let employee = { emp_name: 'Abdul Rawoof', company: 'Tutorials Point', emp_id: 'TP10000', role: 'Software Engineer-Intern', salary: 18000 } let cpyEmployee = JSON.parse(JSON.stringify(employee)) console.log("This is the original object:",employee) console.log("This is the new copied object:",cpyEmployee) cpyEmployee.emp_name = 'B Jason' cpyEmployee.emp_id = 'TP9999' cpyEmployee.role = 'Content Writing-Intern' console.log("The copied object with updations is:",cpyEmployee)

Updated on: 02-Sep-2022

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements