How to destroy keys from an array (ES6)

We just made this code based on guesswork, and it worked. I am sure this is acceptable. I just want to make sure:

const state = { inProgress: true }
const actions = 'COMPLETE_RICE'
const change = { inProgress: false, rice: 'cooked' }

// Is this destructuring OK?
const {
  0: newState,
  1: newActions,
  2: newChange,
} = [state, actions, change]

console.log('New State:', newState)
console.log('New Actions:', newActions)
console.log('New Change:', newChange)
Run codeHide result

Is there a better way to do this?

Any problems or violations?

I can not find any examples of this and only tried because I recalled that:

['one', 'two', 'three'] can be expressed as an object:

{
  0: 'one',
  1: 'two',
  2: 'three'
}

It’s not exactly specified here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

But it works.

+4
source share
2 answers

You can use an array to assign destructuring . There you do not need indexes because the array gives order.

const state = { inProgress: true }
const actions = 'COMPLETE_RICE'
const change = { inProgress: false, rice: 'cooked' }

// Is this destructuring OK?
const [newState, newActions, newChange] = [state, actions, change];

console.log('New State:', newState)
console.log('New Actions:', newActions)
console.log('New Change:', newChange)
Run codeHide result
+6
source

:

const state = { inProgress: true }
const actions = 'COMPLETE_RICE'
const change = { inProgress: false, rice: 'cooked' }

const [newState, newActions, newChange] = [state, actions, change]

console.log('New State:', newState)
console.log('New Actions:', newActions)
console.log('New Change:', newChange)
Hide result
+2

Source: https://habr.com/ru/post/1689606/


All Articles