2

Still learning React, having trouble finding the solution on this one.

I have a series of arrays in the initialState of a redux slice, i.e

const initialState = {
   sprites: {
      one: [1, 2, 3],
      two: [4, 5, 6],
      three: [7, 8, 9]
   }
}

In the app, when the user clicks on a particular button, among other things, I need to get the length of the relevant array.

Here's an example of the app:

<Component onClick={() => {dispatch(checkArray("one"))}/>

And the reducer:

checkArray: (state, {payload}) => {
   var arrayLength = state.sprites.{payload}.length;
   console.log(arrayLength);
}

Obviously this does not yield the desired effect. Using {payload} just throws an error. But how do I convert the payload in a way that will yield the numerical value of the length of the state.sprites.one.length array?

Thanks

Justin Riley
  • 121
  • 7

2 Answers2

2

Use bracket notation.

state.sprites[payload].length;
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Sweet and simple, this was what I needed, thank you – Justin Riley Jan 17 '23 at 17:24
  • Sorry to bother you, I'd like to expand on my question: say I have a variable in initialState such as ```oneIndex``` that I want to select with the the payload. i.e ```console.log(state.[payload]Index);```. Obviously this doesn't work, is there a way to concatenate the payload to a variable in that way? – Justin Riley Jan 17 '23 at 18:28
  • 1
    @JustinRiley There is no easy way to do that. See https://stackoverflow.com/questions/5187530/variable-variables-in-javascript – Unmitigated Jan 17 '23 at 18:30
  • Once again thank you, bracket notation should work perfectly – Justin Riley Jan 17 '23 at 18:41
2

If you want to access a property of an object using a variable, use the square bracket notation. Use square brackets with the payload variable instead of dot notation and curly braces, like this:

checkArray: (state, {payload}) => {
var arrayLength = state.sprites[payload].length;
console.log(arrayLength);
}