0

So this is a bit of an unusual situation i am in but what i need to do is access the value of an object based on what index its stored in. The problem is that i need it in my Select component of material ui. So the overview is that i store alginment values of a video . the videos show up in a loop which means the select values are repeated and to know if its for the first video i append the index inside the object like this:

Object

Now in order to set the option i have to access this value here : enter image description here

Now the problem is in this loop i cant do something like : halign.halign[index] because obviously that would mean its an array. So long story short how could i do something like :

value={`${halign.halign}${index}`} So basically the end result for value to evaluate is : halign.halign0 and so on for each index. NOTE the outer halign is the main useState object.

Hadi Pawar
  • 1,090
  • 1
  • 11
  • 23

1 Answers1

1

Remember that for JavaScript objects x['y'] and x.y are interchangeable.

So if you need to compute the key you're looking up, use:

halign['halign' + index]

Or template strings if you prefer.

Note this would be a lot easier if you organized your object with an internal array, so you could just do halign[index].

tadman
  • 208,517
  • 23
  • 234
  • 262
  • Yes this worked thank you! I'll accept in a bit its not allowing me right now lol. also can you give me like a reference to what you said above about x[y] and x.y being same thing for objects i didn't know that yet. Thank you. – Hadi Pawar Apr 30 '20 at 20:10
  • This is covered in [JavaScript 101](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects), so be sure to check out the MDN introduction to it. – tadman Apr 30 '20 at 20:11
  • 1
    `x['y']` and `x.y` are interchangeable, but `x[y]` would imply that `y` is an identifier which could be any value, which is not the same as `x.y`. – Emile Bergeron Apr 30 '20 at 20:11
  • 1
    @EmileBergeron Good point, updated accordingly. – tadman Apr 30 '20 at 20:12
  • @EmileBergeron yes I understood that. Thank you for your help guys. – Hadi Pawar Apr 30 '20 at 20:12