This post will discuss how to create a copy of an object in JavaScript.

1. Using Object.assign() function

The Object.assign() method is used to copy all enumerable own properties from the source object to a target object. You can use this method to create a copy of an object without references, as shown below:

Download  Run Code

2. Using Spread operator

With ES6, you can use the Spread operator (...) to create a shallow copy of the object.

Download  Run Code

3. Using jQuery

With jQuery, the $.extend() method can be used to create a shallow copy of an object. It works by copying all non-nullish properties from one object to another object.

Download Code

 
If the first argument to $.extend is true, it performs a deep copy.

4. Using Underscore/Lodash Library

If you’re already using the Underscore or Lodash library, you can use the _.clone method for creating a shallow copy of the specified object.

Download Code

 
Alternatively, you can use the _.extend method, similar to jQuery’s $.extend() method.

Download Code

5. Custom Routine

In pure JavaScript, you can write a custom routine for copying an object. The following code can be used as a starting point for all your copying needs:

Download  Run Code

That’s all about creating a copy of an object in JavaScript.

 
Also See:

Deep clone an object in JavaScript