Yohohodev

How to copy object in JavaScript

#JavaScript

To copy objects, we can use the following options:

  1. Copying using the spread operator {...}
  2. Copying using the static method Object.assign()
  3. Copying using JSON.stringify() and JSON.parse() methods
  4. Copying using the global method structuredClone()

In the first and second cases, the copying will be shallow, while in the third option, deep copying will be performed.

structuredClone(), unlike the combination of JSON.parse() and JSON.stringify(), allows cloning various types of objects, such as Array, ArrayBuffer, Boolean, Date, Error, Set, Map, RegExp and much more.

Here are examples:

// Using the spread operator
const shop = {
  name: 'Supermarket',
  address: {
    street: 'Street',
  },
};

const copiedShop1 = {
  ...shop,
};

// Using Object.assign(target, source)
const copiedShop2 = Object.assign({}, shop);

// Using JSON.stringify() and JSON.parse()
const copiedShop3 = JSON.parse(JSON.stringify(shop));

// Using structuredClone() method
const copiedShop4 = structuredClone(shop);

// Let's see what will happen if we decide to change some internal values of the keys
copiedShop2.name = 'Market';

console.log(copiedShop1);
console.log(copiedShop2);
console.log(copiedShop3);
console.log(copiedShop4);

// copiedShop2 output:
// {
//   name: 'Market',
//   address: {
//     street: 'Street',
//   },
// }

// copiedShop1, copiedShop3, copiedShop4 output:
// {
//   name: 'Supermarket',
//   address: {
//     street: 'Street',
//   },
// }

// We will see that only in the copiedShop2 the value of the key 'name' has changed.
// But what will happen if we change the 'street' inside the 'address' object?
copiedShop2.address.street = 'Avenue';

console.log(copiedShop1);
console.log(copiedShop2);
console.log(copiedShop3);
console.log(copiedShop4);

// copiedShop1, copiedShop2 output:
// {
//   name: 'Market',
//   address: {
//     street: 'Avenue',
//   },
// }

// copiedShop3, copiedShop4 output:
// {
//   name: 'Supermarket',
//   address: {
//     street: 'Street',
//   },
// }

// We can see that the value of the 'street' key within the 'address' key also changed in the first object. This is an example of shallow cloning.