Sobes.tech
Middle

What object cloning methods do you know?

sobes.tech AI

Answer from AI

There are several ways to clone objects in JavaScript:

  1. Shallow copy — copies only the top-level properties, nested objects remain references.

    • Using Object.assign():
      const clone = Object.assign({}, original);
      
    • Spread operator:
      const clone = {...original};
      
  2. Deep copy — creates a full copy of the object with all nested objects.

    • Serialization and deserialization via JSON (works only with simple objects without functions, dates, etc.):
      const deepClone = JSON.parse(JSON.stringify(original));
      
    • Using specialized libraries, such as lodash:
      const _ = require('lodash');
      const deepClone = _.cloneDeep(original);
      
  3. Implementing your own clone method — if the object contains methods or complex types, you can implement a clone() method inside the class.

The choice of method depends on the object structure and copying requirements. For simple objects, shallow copy is sufficient; for complex objects, deep copy is necessary.