Search code examples
javascriptreactjseslintdestructuring

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'))


Solution

  • Destructuring can be done with computed property:

    const { [arrayName]: arrayToPrint } = myArrays;