Ben
Ben

Reputation: 5626

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

Upvotes: 9

Views: 1250

Answers (2)

Hsaido
Hsaido

Reputation: 125

A simply way to do that is to use Object.entries(myArrays) .

/* example: expected output of console.log(Object.entries(myArrays)[1]) is ["arrayTwo": Array ["two"]]

Upvotes: 0

Estus Flask
Estus Flask

Reputation: 222498

Destructuring can be done with computed property:

const { [arrayName]: arrayToPrint } = myArrays;

Upvotes: 11

Related Questions