Ivan Durst
Ivan Durst

Reputation: 1163

How to destructure and copy an array simultaneously?

I know you can copy an array with the spread operator:

const itemsArr = [...this.state.itemsArr];

and you can destructure an array that's an object key's value:

const { itemsArr } = this.state

Is there a way to combine them into one step? Pseudocode:

const { itemsArr } = [...this.state]

or

const { [...itemsArr] } = this.state

EDIT: Is there a way to combine them into one step, so as to avoid typing "itemsArr" twice?

Upvotes: 5

Views: 2982

Answers (1)

dziraf
dziraf

Reputation: 3653

It can be done by destructuring itemsArr from a copy of state:

const { itemsArr } = JSON.parse(JSON.stringify(this.state))

The strong point of this is that your nested objects are cloned, so your state.itemsArr is copied too and modifying itemsArr won't change the array in state. The disadvantage is that if your state object contains functions, they won't be accessible using this method plus you can question the performance.

Another way to copy state is by using Object.assign:

const { itemsArr } = Object.assign({}, this.state)

With this you can access your functions inside of state but it makes a shallow copy, so state.itemsArr won't be cloned.

ECMAScript2018 actually has a spread operator that works with JSON objects:

const { itemsArr } = { ...this.state }

https://codesandbox.io/s/32qvzjy2op (look at your browser's console, the one in the tool is bad).

But then again, it only makes a shallow copy.

The best way would be to write/import a deepCopy function that clones the object with it's nested properties and functions.

https://lodash.com/docs#cloneDeep

Upvotes: 2

Related Questions