5

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?

8
  • 3
    You mean something like const {itemsArr: [...itemsArr]} = this.state;? You could also rename the variable: const {itemsArr: [...renamedArray]} = this.state;. Commented Aug 25, 2018 at 23:41
  • @Xufox hadn't thought of that way - essentially the same as const itemsArr = [...this.state.itemsArr] correct? Goal is to avoid typing "itemsArr" twice - I'll add that note to my question. Thanks! Commented Aug 25, 2018 at 23:53
  • No, you cannot without retyping Commented Aug 25, 2018 at 23:59
  • 1
    Currently, const {[...itemsArr]} = this.state is a SyntaxError, though I don’t have the knowledge of the spec to explain why… Maybe, this could become valid syntax in the future. Commented Aug 26, 2018 at 0:02
  • 1
    Why must you try to shorten you code so much with quirky syntax by combining destructuring? Just make the code readable. Commented Aug 26, 2018 at 0:02

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

The ECMAScript2018 snippet is closest to what I was looking for, thanks. +1 for Object.assign, didn't think of that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.