How to copy an object in JavaScript?

Copy JavaScript object is a little tricky. We can do deep copy at the same time we can do the shallow copy. It depends on the requirements.

The deep copy of JavaScript objects can be done in different ways. Let’s consider the following JavaScript object:

Deep copy by JSON.parse and JSON.stringify:

The deep copy of an object can be done by using JSON.stringify and JSON.parse with data loss. We can use JSON.parse(JSON.stringify(obj)) if the object does NOT the have followings.

If the object has the following types then the cloned object will lose data.

  • Dates,
  • functions,
  • undefined,
  • Infinity,
  • RegExps,
  • Maps,
  • Sets,
  • Blobs,
  • FileLists,
  • ImageDatas,
  • sparse Arrays,
  • Typed Arrays or
  • other complex types
// Example 
    const obj = {
        string: 'string',
        number: 123,
        bool: false,
        nul: null,
        getName: () => 'Joe Smith', // lost
        date: new Date(),  // string
        undef: undefined,  // lost
        inf: Infinity,  // forced to 'null'
        regex: /.*/,  // lost
    };

    console.log(obj);
    console.log(typeof obj.date);  //  object
    const clonedObj = JSON.parse(JSON.stringify(obj));
    console.log(clonedObj);
    console.log(typeof clonedObj.date);  // String

Output of the cloned object

    // clonedObj looks like this: 
    clonedObj = {
        "string": "string",
        "number": 123,
        "bool": false,
        "nul": null,
        "date": "2021-08-29T02:29:37.997Z",
        "inf": null,
        "regex": {}
    }

By using standard libarary:

We should not reinvent the wheel. If our project has a library that has object cloning support we should consider using that.

lodashcloneDeep; can be used if the project have lodahs library installed.

Reference: