(Deep) Cloning objects in Javascript

February 22, 2020

Cloning objects in Javascript (and in other language) is a tricky task. JS doesn’t store the object value in your variable or in your constant, instead, store a pointer to the object value (the object reference).

Even when you passes an object to a function or method, you are passing this object by reference, not the value.

This picture perfectly shows the difference.

![By reference and by value](/images/pass-by-reference-vs-pass-by-value-animation.gif)

As you can see, if you pass (or copy) an object by reference and then change any property, the ‘source’ object’s property also changes.

In any example I’ll use the object below

1
2
3
4
5
6
7
8
9
10
11
const sourceObject = {
l1_1: {
l2_1: 123,
l2_2: [1, 2, 3, 4],
l2_3: {
l3_1: 'l3_3',
l3_3: () => 'l3_3'
}
},
l1_2: 'My original object'
}

‘Standard’ cloning

We’ll use a ‘standard‘ cloning by assign the source value to other constant

1
2
3
4
5
6
7
8
9
10
11
12
const copiedObject = sourceObject

console.log('sourceObject', sourceObject.l1_2)
// My original object --> ✔️

clonedObject.l1_2 = 'My cloned object'

console.log('clonedObject', clonedObject.l1_2)
// My original object --> ✔️

console.log('sourceObject', sourceObject.l1_2)
// My original object --> ❌

Edit practical-violet-dki61

As I said before, when I change property l1_2 on cloned object, the value also changes on the source object.

Using this strategy, you are not copying the object at all.

Using spread operator

This time I’ll use the spread operator, that ‘returns’ every element in the object individually.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
console.log('sourceObject l1_2', sourceObject.l1_2)
// My original object --> ✔️
console.log('sourceObject l1_1.l2_1', sourceObject.l1_1.l2_1)
// 123 --> ✔️

const clonedObject = { ...sourceObject }
clonedObject.l1_2 = 'My cloned object'

console.log('clonedObject', clonedObject.l1_2)
// My cloned object --> ✔️
console.log('sourceObject', sourceObject.l1_2)
// My original object --> ✔️

clonedObject.l1_1.l2_1 = '321'

console.log('clonedObject l1_1.l2_1', clonedObject.l1_1.l2_1)
// 123 --> ✔️
console.log('sourceObject l1_1.l2_1', sourceObject.l1_1.l2_1)
// 123 --> ❌️

Edit sleepy-rain-1gtsb

Now property l2_1 is copied by value, we can change it and original object l2_1 keeps original value, but if when I changed l1_1.l2_1 (2th depth property) we get the same as the first attempt.

Spread operator do a shallow copy of the object. Only first level depth properties are copied by value, the nested ones keeps copying by reference.

Using Object.assign

Like spread operator, just do a shallow copy, then I will not create the example, trust me, you will get the same result.

1
const clonedObject = Object.assign({}, sourceObject)

Using JSON.parse and JSON.stringify

This is a simple and fast way to deep clone an object, the point is convert the object to string with JSON.stringify and then get an object from the string using JSON.parse

Lets do it

1
2
3
4
5
6
7
8
const clonedObject = JSON.parse(JSON.stringify(sourceObject))

clonedObject.l1_1.l2_1 = '321'

console.log('clonedObject l1_1.l2_1', clonedObject.l1_1.l2_1)
// 321 --> ✔️
console.log('sourceObject l1_1.l2_1', sourceObject.l1_1.l2_1)
// 123 --> ✔

Everything seems fine! 🎉
But, did you notice l1_1.l2_3.l3_3 property is a function? 😢

1
2
3
4
console.log('clonedObject l1_1.l2_3.l3_3', clonedObject.l1_1.l2_3.l3_3)
// undefined --> ❌️
console.log('sourceObject l1_1.l2_3.l3_3', sourceObject.l1_1.l2_3.l3_3)
// function l3_3() {} --> ✔️

Edit xenodochial-frost-q8k71

Oh, oh, functions are not copied using that method, then, what could we do? The solution is iterate every nested property in the object and use, for example, the spread operator method. Hard and dirty work.

Loadash to the rescue

Lodash is a modular utility library that adds many funcionalities, and one of them is cloneDeep that do exactily we need: clone (deep) an object through nested properties, keeping all value types, even functions.

1
2
3
4
5
6
7
8
import { cloneDeep } from 'lodash'

const clonedObject = cloneDeep(sourceObject)

console.log('clonedObject l1_1.l2_3.l3_3', clonedObject.l1_1.l2_3.l3_3)
// function l3_3() {} --> ✔️
console.log('sourceObject l1_1.l2_3.l3_3', sourceObject.l1_1.l2_3.l3_3)
// function l3_3() {} --> ✔️

Edit trusting-currying-2o6uf

Performance

We’ll copy source object 10.000 times using each method to compare time elapsed. Compare memory usage is no sense because Object.assign and Spread Operator method are not copying nested property by value.

Results in my browser are following:

  • Object.assign clone elapsed time: 4ms
  • Spread operator clone elapsed time: 22ms
  • JSON clone elapsed time: 47ms
  • Lodash clone elapsed time: 92ms

As you can see, if you only need to do a shallow clone Object.assign is faster solution, and if you only need to clone values in nested properties (not functions or symbols), JSON.parse(JSON.stringify()) could be a faster solution. But if you want make sure that all values are copied you must use lodash or a similar solution.

Test yourself in codesandbox!

Edit romantic-shannon-epf1o

Header picture: unsplash-logoKaren Lau
To show the comments is mandatory accept cookie policy.

Front-end and back-end developer.
#formula1, good conversations and small details lover.