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

in #javascript8 years ago

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:

var originalObject = [
  {"first":"Gretchen","last":"Kuphal","email":"[email protected]","address":"416 Lesch Road","created":"March 1, 2012","balance":"$9,782.26"},
{"first":"Morton","last":"Mayer","email":"[email protected]","address":"1602 Bernhard Parkway","created":"April 29, 2017","balance":"$6,596.11"},
{"first":"Catalina","last":"Daugherty","email":"[email protected]","address":"11893 Kali Vista","created":"October 16, 2008","balance":"$6,372.86"},
{"first":"Orpha","last":"Heaney","email":"[email protected]","address":"8090 Chris Stream","created":"November 21, 2015","balance":"$9,596.26"},
{"first":"Reva","last":"Mohr","email":"[email protected]","address":"0291 Kailyn Stravenue","created":"November 6, 2014","balance":"$4,768.37"},
{"first":"Loma","last":"Keeling","email":"[email protected]","address":"84460 Samson Knoll","created":"June 13, 2017","balance":"$9,361.16"}
];

var duplicateObject = originalObject;

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 ”.

originalObject[0].first = "Ray";

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!!

So how do we fix this?

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

var duplicateObject = JSON.parse(JSON.stringify( originalObject ));

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

originalObject[0].first = "Ray";

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

Originally published at Raymon Schouwenaar.

Sort:  

Congratulations @mrfrontend! You received a personal award!

1 Year on Steemit

Click here to view your Board of Honor

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @mrfrontend! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.080
BTC 61714.34
ETH 1618.58
USDT 1.00
SBD 0.40