clonar-objetos-en-javascript

Cloning Objects in JavaScript

  • 5 min

Cloning an object involves creating an independent copy that can be modified without affecting the original object.

This is especially important because in JavaScript, all objects are reference types.

This means that when you assign an object to a new variable, both variables point to the same object in memory. If you modify one, the other will also be affected:

const original = { name: "Juan", age: 25 };
const copy = original;

copy.name = "María";
console.log(original.name); // "María" (the original object also changed)
Copied!

To avoid unwanted side effects, it is necessary to clone objects instead of simply copying the reference.

For this post, it’s very important that you understand what a value type and a reference type are.

Shallow Cloning

Shallow cloning (shallow copy) creates a new instance of an object and copies the top-level properties.

However, if any of these properties is an object itself, only the reference will be copied.

MethodCloning TypeNestedSpecial ValuesComplexity
Spread operatorShallowLow
Object.assign()ShallowLow

Using the spread operator ...

The spread operator (...) is a modern and concise way to clone an object. This method creates a shallow copy of the object, meaning it copies the top-level properties, but not nested objects or arrays.

const original = { name: "Juan", age: 25 };
const clone = { ...original };

clone.name = "María";
console.log(original.name); // "Juan" (the original is not modified)
Copied!

However, if the object has nested properties, these will still share references with the original:

const original = { name: "Juan", details: { age: 25, city: "Madrid" } };
const clone = { ...original };

clone.details.city = "Barcelona";
console.log(original.details.city); // "Barcelona" (the original is affected)
Copied!

Using Object.assign()

Object.assign() is another way to perform a shallow clone. This method copies the own properties of an object (not inherited ones) to the target object.

const original = { name: "Juan", age: 25 };
const clone = Object.assign({}, original);

clone.name = "María";
console.log(original.name); // "Juan"
Copied!

Like the spread operator, this method does not clone nested objects.

Deep Cloning

Deep cloning (deep copy) creates a complete copy of an object, including all nested objects.

This ensures that modifications to the copy do not affect the original object (it’s the “real” cloning).

MethodCloning TypeNestedSpecial ValuesComplexity
structuredClone()DeepLow
JSON.parse(JSON.stringify)DeepMedium
_.cloneDeep() (Lodash)DeepMedium
Manual CloningDependsDependsHigh

Using structuredClone()

Starting from ES2021, JavaScript introduced the structuredClone method, which allows performing deep clones natively.

const original = { name: "Juan", details: { age: 25, city: "Madrid" } };
const clone = structuredClone(original);

clone.details.city = "Barcelona";
console.log(original.details.city); // "Madrid"
Copied!

Limitations

  • Not available in older versions of JavaScript.
  • May not be supported in all browsers.

Using JSON

A simple technique to clone objects that do not contain methods or non-serializable values (like functions, undefined, or circular properties) is to use JSON.stringify() and JSON.parse().

const original = { name: "Juan", details: { age: 25, city: "Madrid" } };
const clone = JSON.parse(JSON.stringify(original));

clone.details.city = "Barcelona";
console.log(original.details.city); // "Madrid"
Copied!

Limitations

  • Does not work if the object contains functions, undefined values, or circular properties.
  • Converts special values like Date to strings.

Using external libraries

When you need a robust solution for cloning complex objects, you can use libraries like Lodash. Lodash’s cloneDeep method performs a complete deep clone.

import _ from "lodash";

const original = { name: "Juan", details: { age: 25, city: "Madrid" } };
const clone = _.cloneDeep(original);

clone.details.city = "Barcelona";
console.log(original.details.city); // "Madrid"
Copied!

Manual Cloning

In certain cases, especially if the object has specific structures or you need to optimize performance, you can clone an object manually by iterating through its properties.