Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destructure keys out of an array (ES6)

We just made this code based on a hunch, and it worked. I'm pretty sure it's 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)

Is there a better way to do this?

Any concerns or violations?

I can't find any examples of this and only tried it because I recalled that:

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

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

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

But, it works.

like image 864
agm1984 Avatar asked Jan 29 '23 04:01

agm1984


2 Answers

You could use an array for a destructuring assignment. There you need no indices, because the array gives the 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)
like image 159
Nina Scholz Avatar answered Feb 02 '23 00:02

Nina Scholz


Instead of destructuring an array as an object, use array destructuring:

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)
like image 45
Ori Drori Avatar answered Feb 01 '23 23:02

Ori Drori