How to copy an array of objects to another array without object reference in JavaScript?

Sometimes, we want to copy an array of objects to another array without object reference in JavaScript.

In this article, we’ll look at how to copy an array of objects to another array without object reference in JavaScript.

How to copy an array of objects to another array without object reference in JavaScript?

To copy an array of objects to another array without object reference in JavaScript, we use some JSON methods.

For instance, we write

const tempArray = JSON.parse(JSON.stringify(mainArray));

to call JSON.stringify with mainArray to convert the array to a JSON string.

Then we call JSON.parse with the string to convert it back to an array to make a copy.

This works if mainArray is an array with plain JavaScript objects or primitive values.

Conclusion

To copy an array of objects to another array without object reference in JavaScript, we use some JSON methods.