How to clone a deep object in react-native

Ridmal Madushanka
Jan 6, 2019 · 1 min read

I was stuck in a error which saying “Attempted to assign to readonly property” when i tried to add new element in the clone object of the redux state.I used spread operator , And it work properly in the emulator ( in my case ) . But when it comes to real devices it don’t work.

const userData = {… reduxState.UserData}

So i was searching for the solution. And this spread operator cannot clone “deep objects”. What i meant by the “deep objects”. Here is one example for Deep object.

Image for post
Image for post
example for deep Object.

So what we gonna do ?

I found many alternative from the Internet for this problem. But the the best option is lodash CloneDeep method. :) .It can be very costly option which will take some time to execute. But it can perfectly clone the deep object and help to handle read only objects.(Mainly you work with redux states)

import _ from “lodash”;

Var newObject = _.cloneDeep(deepObj);

newObject will be a exact clone of the deep Object and it will be not equal to the deepObj.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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