JavaScript

How to clone an object in JavaScript  (deep clone)

April 18, 2022

How to clone an object in JavaScript  (deep clone)

In this article you will learn how to clone an object in JavaScript – a concept also called deep clone, using pure JS!

clone an object in JavaScript thumb

What’s up programmer, ok? Let’s see how to clone an object in JavaScript, in the fastest way and also with performance!

The simplest and most effective way to perform this action is using pure JS, and compatible with browsers, i.e. ES5 and below

We must convert the object into a string and then into JSON, all using JavaScript’s JSON object

See it in action:

let obj = {
 name: 'Matheus'
}

let obj2 = JSON.parse(JSON.stringify(obj));

console.log(obj2);

This way the object will be cloned and you will be able to use all its properties and methods existing in the original object

Cloning with ES6

If there is no problem in the JavaScript version, that is, you transpile the code

You can now use a syntax that came with ES6, using Objet’s assign method

See also in practice:

let obj = {
 name: 'Matheus'
}

let obj2 = Object.assign({}, obj);

console.log(obj2);

Simpler syntax and it also looks less gimmicky, doesn’t it? 😀

But be careful with the most outdated browsers, assing may not work!

Conclusion

In this article we learned how to clone an object in JavaScript, using samples both in ES6 and in ES6

It is good to be aware of the browser version that the project has to support, as the assign may not work in older browsers

Do you want to learn more about JS? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x