Sobes.tech
Middle+

How can you copy an object in JavaScript? What methods do you know?

sobes.tech AI

Answer from AI

In JavaScript, there are several ways to copy an object:

  1. Shallow copy:

    • Using Object.assign():
      const copy = Object.assign({}, original);
      
    • Spread operator:
      const copy = {...original};
      

    These methods only copy the first level of properties; nested objects remain references.

  2. Deep copy:

    • Via JSON serialization:

      const deepCopy = JSON.parse(JSON.stringify(original));
      

      But this method does not copy functions, undefined, symbols, and does not work with cyclic references.

    • Using specialized libraries, such as lodash:

      const _ = require('lodash');
      const deepCopy = _.cloneDeep(original);
      
  3. Recursive copying: You can write your own function for deep copying, traversing all nested objects.

The choice of method depends on the structure of the object and the copying requirements.

How can you copy an object in JavaScript? What… - sobes.tech