Sobes.tech
Middle

How to copy an object to get a new instance instead of a reference copy?

sobes.tech AI

Answer from AI

To copy an object and obtain a new instance rather than a reference to the original object, you can use several approaches in JavaScript:

  1. Shallow copy — copies only the first level of properties:
const original = { a: 1, b: { c: 2 } };
const copy = { ...original };
// or
const copy2 = Object.assign({}, original);

However, nested objects will be references to the same objects.

  1. Deep copy — creates a completely independent copy, including nested objects:
  • Via serialization:
const deepCopy = JSON.parse(JSON.stringify(original));

Cons: does not copy functions, dates, undefined, and other special types.

  • Using specialized libraries, such as lodash:
import _ from 'lodash';
const deepCopy = _.cloneDeep(original);

Thus, for full copying of an object, it is better to use deep copying to avoid shared references to nested objects.

How to copy an object to get a new instance instead… - sobes.tech