How to make a real copy of a JavaScript Array with Objects (without a reference)

It happens a lot that you want to copy a variable, with an Object or Array, to manipulate the data and use it afterward. But when we create an array of users and make a copy in a new variable, like this:

It will keep a reference from “duplicateObject” to “originalObject”. This is also called a shallow copy.

To show you that it will keep its reference, we gonna change the first name of the first user in the “originalObject”.

Then log the “originalObject” and “duplicateObject” and the result will show you that both are changed! In a lot of cases, you don’t want this to happen!!

We can do the trick with JSON.stringify and JSON.parse method.

And if we now change the first name of the first user in the originalObject, the duplicate will not change!

Check it via the console to log the “originalObject” and “duplicateObject”;

Read my other posts

Written by

I write stories about Frontend Dev, JavaScript, Typescript, Angular, NodeJS, Serverless Functions, JAM Stack, FaunaDB, Netlify, Apple, iOS— https://byrayray.dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store