best way to clone an object in javascript

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.


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.


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.


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.


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.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe