0

For example, if I have a useState with the string "drama" set as its value, can I use the useState's string in the path when accessing data in an object? So console.log(movies[0].drama) would be functionally the same as something like console.log(movies[0].--useStateName--).

Specifically I've got an array of movies with each movie having standard data such as title, release date, rating etc. but each movie also has a data point for every possible genre as a boolean, 0 if it is that genre, 1 if it is not.

If I'm trying to console log if the first movie in the array is a drama, I can console.log(movies[0].drama) and it will give '1', because the movie it's returning is a drama.

Separately from the API, I have an array in the application made up of just the genres as an array of strings, this array has been mapped to a form select input. A useState is being updated with whichever genre is selected in the select input.

So the problem is that I need to be able to use the string saved in the useState when checking for movies that belong to whichever genre is in the useState at the time. So if the useState is the string "drama", I need to be able to do something like console.log(movies[0].<useStateName>) and have it do the exact same thing as console.log(movies[0].drama).

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Marcus
  • 261
  • 1
  • 4
  • 14
  • (Note this is just basic JS - you need to know the language to use the library built on top of it.) – jonrsharpe Apr 22 '23 at 17:39
  • Thanks for the answer, the link does seem to be talking about the problem I meant. I get that it may be basic JS and I'm an idiot for not knowing this, but was your second comment really necessary? Everyone has some obvious gaps in their knowledge sometimes. I'm less than 2 weeks away from handing in my thesis. – Marcus Apr 22 '23 at 17:50
  • 1
    Yeah that comment wasn't necessary, it's clear you had reasonable command of JS, just had a blank in this area. I flagged that comment as unkind. The array access described has no special case for React; it's just an array access in that context. – doppelgreener Apr 22 '23 at 18:17
  • Thank you, yeah it did seem unnecessary, but I wasn't sure if I was just taking it the wrong way. Anyway, it's working now and I understand it, those are the important bits and I'm happy it's solved. – Marcus Apr 22 '23 at 18:44

0 Answers0