Thanks to visit codestin.com
Credit goes to coreui.io

How to Clone an Object in JavaScript

As the creator of CoreUI and with over 25 years of software development experience, I’ll show you the most effective ways to clone objects in JavaScript.

You can clone objects in JavaScript using the spread operator (...) for shallow cloning or structuredClone() for deep cloning.

// Shallow clone with spread operator
const originalObject = { name: 'John', age: 30, city: 'New York' }
const clonedObject = { ...originalObject }

// Deep clone with structuredClone (modern browsers)
const nestedObject = {
  user: { name: 'John', preferences: { theme: 'dark' } },
  settings: ['notifications', 'privacy']
}
const deepCloned = structuredClone(nestedObject)

// Alternative deep clone with JSON methods
const jsonCloned = JSON.parse(JSON.stringify(nestedObject))

The spread operator creates a shallow copy, meaning nested objects are still referenced from the original. For shallow cloning, you can also use Object.assign({}, originalObject). When you need to clone nested objects, use structuredClone() which handles complex data types including dates, regular expressions, and circular references. The JSON method is widely supported but has limitations with functions, undefined values, and special objects.

Best Practice Note:

In CoreUI components, we frequently use object cloning for state management and configuration objects. Choose shallow cloning for simple objects and deep cloning when dealing with nested component configurations to prevent unwanted side effects in your UI components.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to round a number to two decimal places in JavaScript
How to round a number to two decimal places in JavaScript

What Does javascript:void(0) Mean?
What Does javascript:void(0) Mean?

Understanding and Resolving the “Objects Are Not Valid as a React Child” Error in React Development
Understanding and Resolving the “Objects Are Not Valid as a React Child” Error in React Development

What is JavaScript Array.pop() Method?
What is JavaScript Array.pop() Method?

Answers by CoreUI Core Team