DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Shallow and Deep Copies in JavaScript: What’s the Difference?
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide

Trending

  • Designing a Java Connector for Software Integrations
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • AI Agents: A New Era for Integration Professionals
  • Securing the Future: Best Practices for Privacy and Data Governance in LLMOps
  1. DZone
  2. Coding
  3. Java
  4. (Deep) Cloning Objects in JavaScript

(Deep) Cloning Objects in JavaScript

Cloning objects in JavaScript (and in other languages) is a tricky task. Let's see different options and check the performance.

By 
Sergio Carracedo user avatar
Sergio Carracedo
·
Dec. 09, 22 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
5.4K Views

Join the DZone community and get the full member experience.

Join For Free

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

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

JavaScript
 
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 assigning the source value to another constant.

JavaScript
 
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 --> ❌


As I said before, when I change the property l1_2 on the 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, which 'returns' every element in the object individually.

JavaScript
 
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)
// 321 --> ✔️
console.log('sourceObject l1_1.l2_1', sourceObject.l1_1.l2_1)
// 321 --> ❌️ // Should keep returning 123 if the clone was complete


Lodash to the Rescue

Lodash is a modular utility library that adds many functionalities, and one of them is cloneDeep, which does exactly what we need to clone (deep) an object through nested properties, keeping all value types, even functions.

JavaScript
 
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() {} --> ✔️


Performance

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

The results in my browser are the 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 the faster solution over the spread operator, 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 to make sure that all values are copied, you must use Lodash or a similar solution.

Cloning JavaScript Java performance

Published at DZone with permission of Sergio Carracedo. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Shallow and Deep Copies in JavaScript: What’s the Difference?
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!