How can I remove the read-only property of an object when I clone/copy it?

Viewed 2463

I want to be able to copy/clone the store state and modify it locally. How can I copy the object and get rid of the read-only property?

let a = store.getState();
console.log(a.property) // 'property'
let b = copy(a)
b.property = 'newProperty';
console.log(b.property) // 'newProperty'
2 Answers

One way is that you can get state from store and then spread it into a new object.

Like:

const state = store.getState()

const newState = {...state}

Now, you can modify state object.

But, if you have multi level objects in state then use JSON.stringify and then use JSON.parse to parse it.

Like this.

const state = store.getState();

const newState = JSON.parse(JSON.stringify(state));

It will make a whole new clone and now you can modify state.

I recommend here using JSON.stringify because you can have multi level objects in your state. And spread only do shadow copy.

Copy using

let b = JSON.parse(JSON.stringify(a))
Related