How do Clone objects in JavaScript

How do Clone objects in JavaScript

Cloning an object in JavaScript a task that is almost always used in any project, to clone everything from simple objects to the most complicated ...

Because objects in #JavaScript are references values, you can't simply just copy using the =. But no worries, here are 3 ways for you to clone an object

const food = { beef: '🥩', bacon: '🥓' }


// "Spread"
{ ...food }


// "Object.assign"
Object.assign({}, food)


// "JSON"
JSON.parse(JSON.stringify(food))

// RESULT:
// { beef: '🥩', bacon: '🥓' }

Objects are Reference Types

Your first question might be, whey can't I use =. Let's see what happens if we do that:

const obj = {one: 1, two: 2};

const obj2 = obj;

console.log(
  obj,  // {one: 1, two: 2};
  obj2  // {one: 1, two: 2};
)

So far, both object seems to output the same thing. So no problem, right. But let's see what happens if we edit our second object:

const obj2.three = 3;

console.log(obj2);
// {one: 1, two: 2, three: 3}; <-- ✅

console.log(obj);
// {one: 1, two: 2, three: 3}; <-- 😱

WTH?! I changed obj2 but why was obj also affected. That's because Objects are reference types. So when you use =, it copied the pointer to the memory space it occupies. Reference types don't hold values, they are a pointer to the value in memory.

Using Spread

Using spread will clone your object. Note this will be a shallow copy. As of this post, the spread operator for cloning objects is in Stage 4. So it's not officially in the specifications yet. So if you were to use this, you would need to compile it with Babel (or something similar).

const food = { beef: '🥩', bacon: '🥓' };

const cloneFood = { ...food };

console.log(cloneFood); 
// { beef: '🥩', bacon: '🥓' }

Using Object.assign

Alternatively, Object.assign is in the official released and also create a shallow copy of the object.

const food = { beef: '🥩', bacon: '🥓' };

const cloneFood = Object.assign({}, food);

console.log(cloneFood);
// { beef: '🥩', bacon: '🥓' }

Using JSON

This final way will give you a deep copy. Now I will mention, this is a quick and dirty way of deep cloning an object. For a more robust solution, I would recommend using something like lodash

const food = { beef: '🥩', bacon: '🥓' };

const cloneFood = JSON.parse(JSON.stringify(food))

console.log(cloneFood); 
// { beef: '🥩', bacon: '🥓' }

Lodash DeepClone vs JSON

Here's a comment from the community. Yes, it was for my previous post, How to Deep Clone an Array. But the idea still applies to objects.

Alfredo Salzillo: I'd like you to note that there are some differences between deepClone and JSON.stringify/parse.

  • JSON.stringify/parse only work with Number and String and Object literal without function or Symbol properties.
  • deepClone work with all types, function and Symbol are copied by reference.

Here's an example:

const lodashClonedeep = require("lodash.clonedeep");

const arrOfFunction = [() => 2, {
    test: () => 3,
}, Symbol('4')];

// deepClone copy by refence function and Symbol
console.log(lodashClonedeep(arrOfFunction));
// JSON replace function with null and function in object with undefined
console.log(JSON.parse(JSON.stringify(arrOfFunction)));

// function and symbol are copied by reference in deepClone
console.log(lodashClonedeep(arrOfFunction)[0] === lodashClonedeep(arrOfFunction)[0]);
console.log(lodashClonedeep(arrOfFunction)[2] === lodashClonedeep(arrOfFunction)[2]);

The JSON method has troubles with circular dependencies. Furthermore, the order of properties in the cloned object may be different.

Shallow Clone vs Deep Clone

When I used spread ... to copy an object, I'm only creating a shallow copy. If the array is nested or multi-dimensional, it won't work. Let's take a look:

const nestedObject = {
  country: '🇨🇦',
  {
    city: 'vancouver'
  }
};

const shallowClone = { ...nestedObject };

// Changed our cloned object
clonedNestedObject.country = '🇹🇼'
clonedNestedObject.country.city = 'taipei';

So we changed our cloned object by changing the city. Let's see the output.

console.log(shallowClone);
// {country: '🇹🇼', {city: 'taipei'}} <-- ✅

console.log(nestedObject);
// {country: '🇨🇦', {city: 'taipei'}} <-- 😱

A shallow copy means the first level is copied, deeper levels are referenced.

Deep Copy

Let's take the same example but apply a deep copy using "JSON"

const deepClone = JSON.parse(JSON.stringify(nestedObject));

console.log(deepClone);
// {country: '🇹🇼', {city: 'taipei'}} <-- ✅

console.log(nestedObject);
// {country: '🇨🇦', {city: 'vancouver'}} <-- ✅

As you can see, the deep copy is a true copy for nested objects. Often time shallow copy is good enough, you don't really need a deep copy. It's like a nail gun vs a hammer. Most of the time the hammer is perfectly fine. Using a nail gun for some small arts and craft is often case an overkill, a hammer is just fine. It's all about using the right tool for the right job 🤓

Performance

Unfortunately, I can't write a test for spread because it's not officially in the spec yet. Nevertheless, I included it in the test so you can run it in the future. But the result shows Object.assign is a lot faster than JSON.

javascript json web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.

Progressive Web App Development

Hire Full Stack Developer from HireFullStackDeveloperIndia.com to build user-centric & robust Progress Web App Development Solutions in India.

Best Web and App Development Company in Ahmedabad

Contact DataPierce for any questions or queries you have about website development, designing, marketing projects or any small or enterprise software development.