DEV Community

technicallyty
technicallyty

Posted on

1

Why your JavaScript object might not be copied by assigning it to a new variable.

So you've imported yourself a JS object have you? You've imported it into a react component. Great. You assign it a new variable via the likes of var x = importedJsObj. You change the some of the values in x and hand off the "pure" importedJsObj to another function. Well you're out of luck. It didn't actually copy it.

I found this out the hard way when I needed to filter a subset of a js object, and hand off the original to different function.

Alas, we have lodash - https://lodash.com/

If you're using react, go ahead and type npm i --save lodash

Then, you need to import what you need to use. To solve my specific problem I did import { deepClone } from 'lodash' -https://www.digitalocean.com/community/tutorials/js-deep-cloning-javascript-objects#so-how-can-i-copy-an-object-the-right-way

Then instead of just saying var x = importedJsObj you say var x = deepClone(importedJsObj)

And there you have it. A properly copied js object that won't mutate the original.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay