5 Different Ways to Copy an Object in JavaScript

There are five different ways to copy an Object in JavaScript.

  1. Using the “Object.assign()” method
  2. Using the “Spread operator”
  3. Using the “JSON.parse()” and “JSON.stringify()” methods
  4. Using the “Object.create()” method
  5. Deep copy using a “custom function”.

Method 1: Using the Object.assign() method

Object.assign() copies the values of all enumerable properties from one or more source objects to a target object. The method does not create deep copies of nested objects.

Example

const source = { a: 1, b: 2, c: { d: 3 } };
const target = Object.assign({}, source);

console.log(target);

Output

{ a: 1, b: 2, c: { d: 3 } }

Method 2: Using the Spread operator

The spread operator (…) creates a shallow copy of an object by spreading its properties into a new object. This method does not create deep copies of nested objects.

Example

const source = { a: 1, b: 2, c: { d: 3 } };
const target = { ...source };

console.log(target);

Output

Gender

Method 3: Using the Object.assign() method

This method involves converting the source object to a JSON string using “JSON.stringify()” and then parsing the string back to an object using JSON.parse(). It creates a deep copy of the object but has limitations, such as being unable to copy functions or circular references.

Example

const source = { a: 1, b: 2, c: { d: 3 } };
const target = JSON.parse(JSON.stringify(source));

console.log(target); 

Output

{ a: 1, b: 2, c: { d: 3 } }

Method 4: Using the Object.assign() method

Object.create() function creates a new object with the specified prototype object and properties. It creates a shallow copy of the object, mainly used to inherit properties from another object.

Example

const source = { a: 1, b: 2, c: { d: 3 } };
const target = Object.create(Object.getPrototypeOf(source), 
               Object.getOwnPropertyDescriptors(source));

console.log(target);

Output

{ a: 1, b: 2, c: { d: 3 } }

Method 5: Using the Object.assign() method

You can create a “custom function” to perform a deep copy of an object, including nested objects and arrays. This method is more versatile, as it can handle more complex objects.

Example

function deepCopy(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }

  const copy = Array.isArray(obj) ? [] : {}; 

  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      copy[key] = deepCopy(obj[key]);
    }
  }
  return copy;
}

const source = { a: 1, b: 2, c: { d: 3 } };
const target = deepCopy(source);
console.log(target);

Output

{ a: 1, b: 2, c: { d: 3 } }

That’s it.

Leave a Comment