How to clone object in JavaScript?

An object is an entity which has properties and types. It is a complicated datatype where it can store various data type.

const employee = {
  name:'Anna',
  id:101,
  age:35,
  salary:2000
};

In JavaScript, objects are reference values. To clone objects we cannot use assignment operator (=). Using assignment operator (=)  we are creating only an alias for existing object.

What is Shallow copy?

Shallow copy or clone copies only the actual object. Nested objects are not copied. Since mutable and stored as reference, when assigning object to another variable, we are assigning objects memory address to variable. It is a one-level deep copy.

Using Spread operator:
const employee = {
  name:'Anna',
  id:101,
  age:35,
  salary:2000
};
const empclone = {
  ...employee  // clone object using spread 
};
//changing value in employee
employee.salary=3000;
console.log(empclone);
console.log(employee);
Output:

{name:’Anna’, id:101, age:35, salary:2000}

{name: ‘Anna’, id: 101, age: 35, salary: 3000 }

Here we have created a shallow copy of object.Any change in original object is not reflected in copied object. But if object consists of nested child objects, any change in child object reflects in copied object.

Example:

const data = { name: “Anna”, age: 26, hobbies: [“Jogging”, “Tennis”, “Gym”] }

const dataCopy = { …data }

data.hobbies[0] = “Swimming”

console.log(data.hobbies)

console.log(dataCopy.hobbies)

Output:

[ ‘Swimming’, ‘Tennis’, ‘Gym’ ]

[ ‘Swimming’, ‘Tennis’, ‘Gym’ ]

Here hobbies is nested object and changing its value gets reflected in copy object.

Using Object.assign():

It is an alternative to spread operator. We can copy values and properties from one or more source object to a new object.

Syntax:
const clone = Object.assign({}, object);
Example:
const employee = {
  name:'Anna',
  id:101,
  age:35,
  salary:2000
};
const empclone = Object.assign({}, employee); // copy using Object.assign()
console.log(empclone);
Output:

{name: ‘Anna’, id: 101, age: 35, salary: 2000 }

Here the second argument employee is copied to first argument {} of assign method.

This is also shallow copy like spread operator.

Deep Copy:

In JavaScript deep copy allows us to create a completely independent copy of original object. It has the same properties but does not share the same references as original object. Any change to one object will not reflect in another object. Deep copy is performed using the methods JSON.parse() and JSON.stringify().

Using JSON.parse():
Syntax:
const clone= JSON.parse(JSON.stringify(Objname))
Example:
const employee = {
  name:'Anna',
  id:101,
  age:35,
  salary:2000
};
const empclone = JSON.parse(JSON.stringify(employee));
console.log(empclone);
Output:

{ name: ‘Anna’, id: 101, age: 35, salary: 2000 }

Example:
// Deep Clone
obj = {
  a: 1,
  b: {
    c: 1
  }
};
let cloneObj = JSON.parse(JSON.stringify(obj));
obj.a = 2;
obj.b.c = 2;
console.log(JSON.stringify(obj)); // { a: 2, b: { c: 2}}
console.log(JSON.stringify(cloneObj)); // { a: 0, b: { c: 0}}
cloneObj.a = 4;
cloneObj.b.c = 4;
console.log(JSON.stringify(obj)); // { a: 2, b: { c: 2}}
console.log(JSON.stringify(cloneObj)); // { a: 4, b: { c: 4}}
Output:

{“a”:2,”b”:{“c”:2}}

{“a”:1,”b”:{“c”:1}}

{“a”:2,”b”:{“c”:2}}

{“a”:4,”b”:{“c”:4}}

As you can see from above example that copied object is independent but it can contain incorrect values in some cases. Another drawback is it works well only with primitive datatypes like numbers, strings and Boolean.

To overcome this we have structuredClone() function.

Using structuredClone():

It creates a deep clone of an object. It overcomes many short comings of JSON.parse().

Clone inifitely nested objects and arrays.

Copy circular references.

Clone a many data types like map, set, date, RegEx, etc.,

Transfer any transferable object.

Syntax:
structuredClone(value)
structuredClone(value, options)

value – Object to clone.

Options (optional)- object with properties as follows:

transfer- An array of transferable objects that will be moved rather than cloned to the returned object.

Return value- returns a deep copy of an object.

Supported platforms:
  • Chrome 98
  • Safari 137
  • Firefox 94
  • Node.js 17.0
  • Deno 1.14

On platforms that don’t support we can use polyfills.

Example:
const employee = {
  name:'Anna',
  id:101,
  age:35,
  salary:2000
};
const empclone = structuredClone(employee);
console.log(empclone);
Output:

{name: ‘Anna’, id: 101, age: 35, salary: 2000}

Points to note:
To perform shallow copy:
  • The spread operator
  • The Object.assign() method.
To perform deep copy:
  • The JSON parsing approach
  • The structuredClone() method.

Getting started with JSON in JavaScript

JSON is an acronym of JavaScript Object Notation. It is a storage format derived from JavaScript programming language and it is language independent.It is a text-based data format that is used to store and transfer data. It’s quite important to know while data which we fetch from external API are always in JSON format.

  • It can transport the data from server to client, client to server and server to server.
  • It can generate and store data from user input.
  • It can also build and verify data

JSON Syntax:

JSON objects are in a .json file which is quite similar to object literal syntax which consists of name, value pairs but the format is text only. Both the name and values are quoted in double quotation.

Points to remember:

  • Data is in name/value pair.
  • Curly braces hold objects.
  • Square brackets hold arrays.
  • Data is separated by commas.

If JSON objects are in .js or .html file then the syntax is

In terms of Syntax JSON is similar to JavaScript objects but the name in JavaScript objects are not in double quotes.

JSON Data:

JSON data is written as name and a value pairs. A name/value pair is like field name in double quotes followed by colon (:), then value.

JSON Objects:

As mentioned earlier JSON objects are in curly braces.

JSON Arrays:

JSON arrays are in square brackets.

Here ‘names’ is an array, and it contains 3 objects. Each object is a record of a person.

Accessing JSON Data:

JSON data can be accessed using dot (.) notation.

Output:
Anna
Mills

We can also use square brackets to access JSON data.

JSON vs JavaScript Objects:

JSONJavaScript Objects
The name in name/value pair should be in double quotesThe name can be without double quotes
JSON cannot contain functionsJavaScript objects can contain functions
JSON can be created and used by other programming languagesJavaScript objects can only be used in JavaScript.

Converting JSON to JavaScript Object:

You can convert JSON data to JavaScript object using in-built JSON.parse() function.

Output:

Converting JavaScript object to JSON:

You can convert JavaScript object to JSON using in-built JSON.stringify().

Output:

Keypoints to note:

  • JSON syntax is like Object literal where both name-value pair is in inverted commas.
  • JSON.stringify() Object to JSON
  • JSON.parse() JSON to Object