Skip to content
the poor coder

best way to clone an object in javascript

Poor Man
Published
Reading time
2 min read
On this page

Best Way to Clone an Object in JavaScript#

Cloning an object in JavaScript is a common task, especially when you want to create a copy of an object without modifying the original. There are several ways to clone an object in JavaScript, but the best way depends on your requirements and the complexity of the object.

Using the Spread Operator#

The easiest way to clone a simple object in JavaScript is to use the spread operator. This method creates a new object with the same properties and values as the original object.

Text

const originalObj = {foo: 'bar', baz: 'qux'};
const clonedObj = {...originalObj};

The spread operator works for simple objects, but it doesn't work for objects with nested objects or arrays. In this case, the spread operator only clones the reference to the nested object, not the object itself.

Using JSON.stringify and JSON.parse#

If you need to clone an object with nested objects or arrays, you can use JSON.stringify and JSON.parse. This method creates a deep copy of the object by converting it to a JSON string and then parsing it back into a new object.

Text

const originalObj = {foo: 'bar', nestedObj: {a: 1, b: 2}};
const clonedObj = JSON.parse(JSON.stringify(originalObj));

This method works for complex objects, but it has some drawbacks. It doesn't work for objects with circular references, and it can be slow for very large objects.

Using Object.assign#

The Object.assign method is another way to clone an object in JavaScript. This method creates a new object with the properties and values of the original object.

Text

const originalObj = {foo: 'bar', baz: 'qux'};
const clonedObj = Object.assign({}, originalObj);

This method works for simple objects, but it doesn't work for objects with nested objects or arrays. In this case, the Object.assign method only clones the reference to the nested object, not the object itself.

Using a Custom Function#

If you need more control over the cloning process, you can create a custom function to clone the object. This method allows you to handle nested objects and arrays and to clone objects with circular references.

Text

function cloneObject(obj, hash = new WeakMap()) {
  if (Object(obj) !== obj) return obj; // primitives
  if (hash.has(obj)) return hash.get(obj); // cyclic reference
  const result = obj instanceof Date ? new Date(obj)
               : obj instanceof RegExp ? new RegExp(obj.source, obj.flags)
               : obj.constructor ? new obj.constructor()
               : Object.create(null);
  hash.set(obj, result); // cyclic reference
  return Object.assign(result, ...Object.keys(obj).map(key => ({[key]: cloneObject(obj[key], hash)})));
};

const originalObj = {foo: 'bar', nestedObj: {a: 1, b: 2}};
const clonedObj = cloneObject(originalObj);

This method is more complex than the other methods, but it gives you complete control over the cloning process. It works for objects with nested objects or arrays and for objects with circular references.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC