3 ways to clone objects in JavaScript

Tram Ho

Hello everyone, learning JavaScript surely we must know Object. In some specific problems, sometimes we need to use ‘Clone Objects’ to perform different functions. This article will introduce you to ‘3 ways to clone objects in JavaScript’

Objects are a reference type

First time clone 1 obj I also use the assignment = , log out the results are quite satisfactory

However, when adding / modifying an item, see what happens

Why was the original Object still affected? That’s because Object is a reference type, so when you use = , it copies the pointer to the memory space it occupies, the reference types don’t hold values, they’re a pointer to the value. in memory. So we need to find another way to clone the object without affecting the ‘original’ object.

1. Use Spread

Using Spread will help us clone Obj. Note when using it you may need to compile with Babel

2. Use Object.assign

In addition to the legendary IE, Object.assign support is almost complete, Object.assign is in the official release and we can use it to clone 1 Obj quickly. Read more about Object.assign ()

3. Use JSON

Shallow Clone vs Deep Clone

A slight comparison between “shallow” clone and “deep” clone. Let’s observe the following example

“Shallow” means that we only clone the first level, the deeper level will be interpreted as a reference. And when using method 3

Object.assign vs Spread

Object.assign is a function that modifies and returns the target object . When using

{} is interpreted as a modified object, the target object is not referenced by any variables at that time, but since Object.assign returns the target object, we can store the assigned object. Results in the cloneFood variable

Obviously the value of corn in the food object is wrong, so we can assign the correct value to corn using Object.assign . We really don’t use the return value of the function, but we are modifying the target object that we referenced with the food object.

Spread is a way of copying the properties of an object into a new object

... cause an error, because we use Spread to create a new object and therefore are assigning a completely new object to the food declared with const constants is wrong. The solution is to create a new variable to save the object

or we can use let , var to allow us to assign a completely new object

Conclude

Above I have introduced you to ‘3 ways to Clone Objects in JavaScript’, hoping to help you when working with Objects in JavaScript

If you find a good article, give me +1 upvote. If you like me, click the follow button for more cool stuff. Good luck !


Refer to 3 Ways to Clone Objects in JavaScript

Share the news now

Source : Viblo