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 : 6964  
 
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

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…

Dates in local format with Javascript

In the articles we have about dates in JavaScript we were missing one about how to create dates in local format with JavaScript. That is to say, being able to…

Formatting hours in Javascript

Continuing with the set of articles that talk about internationalisation elements, like the previous one where we talked about relative dates in JavaScript, we will see in this one how…

Request data with prompt in JavaScript

After having published several articles about how to manipulate arrays and dates, today I will publish a post that some of you will find too basic and others will find…

Relative dates in JavaScript

One of the interesting things about the internationalisation library represented in the Int object is the handling of relative dates in Javascript. This handling allows us to represent a date…

How to access webcam and grab an image using HTML5 and Javascript

We often use webcams to broadcast video in real time via our computer. This broadcast can be viewed, saved and even shared via the Internet. As a rule, we need…

The JavaScript forEach loop

We have already talked about how to handle some of loops  types in Javascript including for, for-in and for-off loops. In the case of today we are going to see how…

What are React Hooks and what problems they solve

Working with React, - and before the release of Hooks in version 16.8 -  there was always the possibility to create components in three different ways based on a number of…

Flattening arrays in JavaScript

When we are handling arrays that are arrays or have multiple dimensions it can be very useful to know how to flatten arrays in JavaScript. That is to say, to…

How to populate an array with random numbers in JavaScript

Some of you might think that what we explained in the article on how to populate an array with numbers, apart from the didactic part, would not have much applicability…

How to populate an array with numbers in JavaScript

Populate an array with numbers in JavaScript The first step is to initialise the array. So today we are going to see a simple way to do it and see how…

Top Javascript Libraries and Frameworks Part 2

What are JavaScript frameworks?   JavaScript frameworks are application frameworks that allow developers to manipulate code to meet their particular needs. Web application development is like building a house. You have the option…

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