9

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'))
Ben
  • 5,079
  • 2
  • 20
  • 26
  • For clarity, you can replace `function arrayPrinter(arrayName)` by `arrayName => ` – Nino Filiu Feb 20 '19 at 23:13
  • 1
    What's wrong with `let { arrayTwo } = myArrays; let arrayToPrint = arrayTwo;`? – Nino Filiu Feb 20 '19 at 23:15
  • @NinoFiliu nothing wrong with that at all, and it's probably a better pattern if I refactor my code, but the question still stands ;) – Ben Feb 20 '19 at 23:19
  • @NinoFiliu actually passing the array itself doesn't end up helping me. The use-case I have is updating the state of a parent component from a child, adding to one of several arrays based on a selection in the child component, so the child is telling the parent which value to add to which array (in parent state, and shared with other components). – Ben Feb 20 '19 at 23:30
  • @Ben you can see this https://stackoverflow.com/questions/54605286/what-is-destructuring-assignment-and-what-are-its-uses – Code Maniac Feb 21 '19 at 08:19

2 Answers2

10

Destructuring can be done with computed property:

const { [arrayName]: arrayToPrint } = myArrays;
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
0

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"]]
Hsaido
  • 125
  • 12