DEV Community

technicallyty
technicallyty

Posted on

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.

Top comments (0)