How to deep clone or copy an array of objects using the JSON.stringify() method in JavaScript?

June 14, 2021 - 3 min read

To deep-clone an array of objects in JavaScript, we can first pass the array into the stringify() method on the global JSON object and then use the parse() method on the global JSON object to convert the array string into a valid copy of the same array.

TL;DR

// array of objects
const objsArr = [{ name: "John Doe" }, { name: "Roy Daniel" }];

// first convert the array into a string
// using the JSON.stringify() method
const objsArrStr = JSON.stringify(objsArr);

// conver the string again to array of objects
// using the JSON.parse() method
const objsArrDeepCopy = JSON.parse(objsArrStr);

console.log(objsArrDeepCopy);
// copied array of objects -> [{ name: "John Doe" }, { name: "Roy Daniel" }]

For example let's say we have an array with some objects as its elements like this,

// array of objects
const objsArr = [{ name: "John Doe" }, { name: "Roy Daniel" }];

Now to deep clone the array including the object elements inside it we can use JSON.stringify() to first convert the array into a string. It can be done like this,

// array of objects
const objsArr = [{ name: "John Doe" }, { name: "Roy Daniel" }];

// first convert the array into a string
// using the JSON.stringify() method
const objsArrStr = JSON.stringify(objsArr);

console.log(objsArrStr);

/*
OUTPUT
------

[
    {"name":"John Doe"},
    {"name":"Roy Daniel"}
]
*/

If we look at the above output we can see that the whole array is converted into a string.

Now let's use the JSON.parse() method to convert the above string into a valid JavaScript array of objects, but now the references of all the objects inside the array are also new.

// array of objects
const objsArr = [{ name: "John Doe" }, { name: "Roy Daniel" }];

// first convert the array into a string
// using the JSON.stringify() method
const objsArrStr = JSON.stringify(objsArr);

// conver the string again to array of objects
// using the JSON.parse() method
const objsArrDeepCopy = JSON.parse(objsArrStr);

console.log(objsArrDeepCopy);
// copied array of objects -> [{ name: "John Doe" }, { name: "Roy Daniel" }]

We successfully made a deep copy of the array with all the object elements inside having a new reference to it. Yay! 🎊

See the above code live in JSBin

NOTE: This method will work for those objects or arrays with JSON serializable tokens only and will not work if it has function types and other non-serializable item types inside the objects or arrays.

That's all 😃!

Feel free to share if you found this useful 😃.