clone object in javascript

How to Clone Objects in JavaScript

JavaScript objects are data structures that allow you to store information using key-value pairs, where each value can be a number, string, array or another object. You can use them to store diverse type of data such as strings, arrays, numbers in a single object and access each piece of data using its appropriate key. Sometimes you may need to copy a JavaScript object to be able to work with it further. In this article, we will learn how to clone objects in JavaScript. But since JavaScript objects are reference values, unlike variables, you cannot directly copy them using assignment operator ‘=’. However, there are several ways to do this and we will learn them in this article.


How to Clone Objects in JavaScript

Before you clone object in JavaScript you need to know that there are two types of object cloning in JavaScript – Shallow Clone and Deep Clone. In Shallow Clone, only the first level is copied, the nested levels are simply referenced. So if you change a value in the first level of clone object, it will not change its value in the original object. On the other hand, if you change value in subsequent levels of cloned object, then those values will change in the original object also.

A deep clone is a true copy of an object where each value at each level of object is copied separately. It means no matter which value of cloned object you change, it will not affect the source object.

We will show this difference with an example below.

Now let us look at 3 common ways to clone JS object.


1. Using Spread Operator

Spread operator is basically 3 dots (…) is used to clone an array or JavaScript object. Please note, this will be a shallow copy of the object.

const people = { name: 'jim', age: 25 };

const clone_people = { ...people };

console.log(clone_people);
// { name: 'jim', age: 25 }

You basically need to mention the array or object name immediately after the spread operator as shown above, and enclose it within curly braces {…}

You can also add more values to the clone while cloning, if you want. Here is an example to do so.

const people = { name: 'jim', age: 25 };

const clone_people = { ...people, nick:'batman' };

console.log(clone_people);
// { name: 'jim', age: 25, nick: 'batman' }


2. Using Object.Assign

You can also use Object.assign() function to copy or clone an object. Here is an example to clone the object using assign() function.

const people = { name: 'jim', age: 25 };

const clone_people = Object.assign({}, people);

console.log(clone_people);
// { name: 'jim', age: 25 }

Object.assign takes two arguments, the first one is an empty object or array. The second is the object or array to be copied. The first argument ensures that you don’t mutate the original object.


3. Using Lodash.DeepClone

You can also use Lodash, a third-party library to create a deep copy of an object or array. Here is a simple example to use Lodash to do a deep clone of object. It works with all data types including functions and symbols. Here is an example where we clone an array of functions. You just need to mention the JS object name as input parameter for lodash.clonedeep function.

const lodashClonedeep = require('lodash.clonedeep');

const arrOfFunction = [
  () => 2,
  {
    test: () => 3,
  },
  Symbol('4'),
];

// deepClone copy by refence function and Symbol
console.log(lodashClonedeep(arrOfFunction));

// function and symbol are copied by reference in deepClone
console.log(
  lodashClonedeep(arrOfFunction)[0] === lodashClonedeep(arrOfFunction)[0],
);
console.log(
  lodashClonedeep(arrOfFunction)[2] === lodashClonedeep(arrOfFunction)[2],
);
 

Alternatively, you can also use JSON library to create deep clone for the object. But it works only if your object’s values consist of strings/numbers.

const people = { name: 'jim', age: 25 };

console.log(JSON.parse(JSON.stringify(people)));
// { name: 'jim', age: 25 }


Shallow Clone vs Deep Clone

Now that we have seen the common ways to clone an object, let us learn about the difference between Shallow Copy vs Deep Copy with an example.

Let us say you have the following object.

const nestedObject = {
  flag: '🇨🇦',
  country: {
    city: 'vancouver',
  },
};

Let us say you do a shallow copy of the above object and change the first level value flag, and second level value country.city.

const shallowClone = { ...nestedObject };

// Changed our cloned object
shallowClone.flag = 'IN';
shallowClone.country.city = 'Mumbai';

Now we will print both the original and cloned object.

console.log(shallowClone);
// {country: IN', {city: 'Mumbai'}}

console.log(nestedObject);
// {country: '🇨🇦', {city: 'Mumbai'}}

You will see that changing the city value in cloned object has also changed corresponding value in original object.

Now let us do a Deep clone using JSON library, which is also used to produce Deep Clones, if your object consists of only strings and numbers.

const deepClone = JSON.parse(JSON.stringify(nestedObject));

console.log(deepClone);
// {country: IN', {city: 'Mumbai'}}

console.log(nestedObject);
// {country: '🇨🇦', {city: 'vancouver'}} 

You will find that in this case, changing the values of clone object does not change the corresponding values in original object.

In this article, we have learnt several ways to clone object in JavaScript and also learnt the key difference between Shallow Copy and Deep Copy.

Also read:

How to Replace All Occurrences of String in JavaScript
Python String Slicing
How to Select Rows from Dataframe Using Column Values
How to Rename Column in Pandas
How to Create Pandas Dataframe from Dictionary

Leave a Reply

Your email address will not be published. Required fields are marked *