How to clone objects in JavaScript

by Luigi Nori Date: 11-05-2021 javascript


Primitive and referenced values (objects) behave very differently when we want to make a copy of them.

Primitive values

Let's suppose a variable name that has a primitive value associated with it (number, string, boolean, undefined and null). If we make a copy of this variable name to another variable name2, any modification in the original variable will not imply any change in the second variable as they are primitive values.

 
let name="Silvia";
let name2="";
console.log (name, name2); // returns Silvia, Silvia 
name="Luigi";
console.log (name,name2); // returns Luigi, Silvia

Example 1

 

Values by reference

However, if we do the same operation on values by reference, any change we make in one of the variables will also be reflected in the other variable since both variables point to the same object. (see example 2)

Arrays

To clone arrays, the slice() method is used to create a new copy of the array. This copy can be modified independently without affecting the original array (n3 example 2). If no parameters are passed, it makes an exact copy of the array, but numbers can also be passed as parameters. If only one number is passed, it will determine the value of the index from which we want the copy to be made, while if 2 numbers are passed, we will be marking the beginning and the end.

 
//n.1

  const names= ['Silvia','Luigi','Alex'];
  const names2= names;
  console.log (names, names2); 
  // returns name ['Silvia','Luigi','Alex']
  // returns names2 ['Silvia','Luigi','Alex']
//n.2

  names2[2]="Angelo";
  console.log (names,names2); 
  // returns name ['Silvia','Luigi','Angelo']
  // returns names2 ['Silvia','Luigi','Angelo']


//n.3

  const name2= names.slice();
  names2[2]="Anna";
  console.log (name2,names2); 
  // returns name ['Silvia','Luigi','Angelo']
  // returns names2 ['Silvia','Luigi','Anna']

Example 2

 

Objects

The same happens when the referenced value is an object, any modification in one of its properties will affect both variables (n.2 Example 3). To clone objects, the Object.assign() method is used, which will copy the values of all enumerable properties of one or more source objects to a target object (n.3 Example 3). But this method is only effective for shallow copies of objects, i.e. when our starting object has no other objects as attributes.

 
//n.1
const names= {
name:'Silvia',
surname:'White'
}
const names2= names;
console.log (names, names2); 
// they are exact copies
//n.2
names2.surname='Green';
console.log (names,names2); 
/* returns const names= {
name:'Silvia'
surname:'Green'
}
returns const names2= {
name:'Silvia';
surname:'Green';
}
*/
//n.3
const name2= Object.assign({}, names);
names2.surname="Green";
console.log (names,names2); 
/* returns const names= {
name:'Silvia'
surname:'White'
}
returns const names2= {
name:'Silvia'
surname:'Green'
}
*/

Example 3: Cloning of objects at first level

 

To make a deep copy of objects other methods are used.

As we said, the Object.assign() method was only valid when we were trying to make a shallow copy of the object, that is, when our object does not have other objects as attributes. In these cases, a deep copy of the object is necessary.

A deep copy, unlike a shallow copy, also copies each sub-object recursively until all the objects involved are copied.
What methods can we use for a deep copy of Objects?

JSON.parse(JSON.stringify(obj))

This method converts the object to a string with JSON.stringify() and then converts it back to a JSON.parse() object. This method is effective with simple objects but not when one of the properties is a function (Example 4).

//n.1
const names= {
name:'Silvia',
surname:'White',
social: {
twitter: '@manoweb',
facebook:'ManoWeb'
}
}
const names2= JSON.parse(JSON.stringify(names));
names2.social.facebook='manoagency';
console.log (names, names2); 
/* returns const names= {
name:'Silvia',
surname:'White',
social:{
twitter:@manoweb
facebook:'ManoWeb'
}
}
returns const names2= {
name:'Silvia',
surname:'White',
social:{
twitter:@manoweb
facebook:'manoagency'
}
}
*/

Example 4

 

Exploiting recursive functions in Deep Clone

Another very interesting and elegant way to make deep copies of objects is to use recursive functions (Example 5).

We create a function deepClone(object) to which we pass as an argument the object we want to clone.
Inside the function, a local variable clone is created, which is an empty object where each of the properties that will be cloned from the starting object will be added.

Thanks to a for we go through each and every one of the properties of the object we want to clone.

 
  • If the property is not an object, it is simply cloned and added to the new clone object.
  • If the attribute is an object, the deepClone(value) function is executed again, passing the value of the property (in this case the object) as a parameter, and the same process is repeated.
 
function deepClone(object) {
var clone={};
for (var key in object) {
var value = object[key];
if (typeof(value)!='object') {
clone[key]=value;
} else {
clone[key]=deepClone(value);//Here the object property is also an object.
//By means of a recursive function, what we do is to clone the object that 
//is on the second or next level.
}
}
return clone;
}
deepClone({value1:1,value2:{value3:2}});
//{value1:1,value2:{value3:2}}
deepClone({value1:1,value2:{value3:{value3b:3}}});
//{value1:1,value2:{value3:{value3b:3}}}

Example 5

 
by Luigi Nori Date: 11-05-2021 javascript hits : 7397  
 
Luigi Nori

Luigi Nori

He has been working on the Internet since 1994 (practically a mummy), specializing in Web technologies makes his customers happy by juggling large scale and high availability applications, php and js frameworks, web design, data exchange, security, e-commerce, database and server administration, ethical hacking. He happily lives with @salvietta150x40, in his (little) free time he tries to tame a little wild dwarf with a passion for stars.

 
 
 

Related Posts

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

How to reverse an array in JavaScript

In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop…

How synchronize the scroll of two divs with JavaScript

In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example,…

How to use the codePointAt method in JavaScript

The JavaScript codePointAt method has more or less the same function as the charCodeAt method, used to get the 16-bit Unicode representation of the character at a certain position in…

How to check if a value is a number in JavaScript

In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.   1. Using the isNaN() function   One…

How to use the charCodeAt method in JavaScript

The charCodeAt method is accepted by strings in JavaScript, returning the 16-bit Unicode code of the character at the position we pass as a parameter to the method. The charCodeAt method…

How to use the charAt method in JavaScript

The charAt method is accepted by strings in JavaScript, returning the position of the character passed as a parameter within the string. If the string contains multiple occurrences of the character…

Strings in JavaScript: What they are and how to use them

In this tutorial we are going to explain what strings are and how they are used in JavaScript. The tutorial is intended for people who are learning to program in…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration