Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to destructure in JavaScript via bracket notation?

This is not necessarily an issue, more a curiosity that came up via an ESLint error which led me to wonder if there was a better way that just disabling ESLint for this line.

Consider the code snippet below. ESLint will give an error if the react/destructuring-assignment rule is enabled, preferring

const { arrayToPrint } = myArrays to const arrayToPrint = myArrays[arrayName]

My question is, and I haven't been able to find any reference to this so I'm guessing not, is there a way to move [arrayName] to the lefthand side of the assignment to destructure without a reference to the actual object property?

const myArrays = {
  arrayOne: ['one'],
  arrayTwo: ['two'],
  arrayThree: ['three'],
}

const arrayPrinter = function arrayPrinter(arrayName) {
	const arrayToPrint = myArrays[arrayName]
  
  return arrayToPrint
}

console.log(arrayPrinter('arrayTwo'))
like image 355
Ben Avatar asked Feb 20 '19 23:02

Ben


1 Answers

Destructuring can be done with computed property:

const { [arrayName]: arrayToPrint } = myArrays;
like image 108
Estus Flask Avatar answered Oct 18 '22 09:10

Estus Flask