javascriptreactjsdatabaseapirelational

React how to address a key from string name


Ok, so I have a database with data sets in it. the application performs a base API call to retrieve that base data set containing all other data sets. I will receive a string variable with the name of the key I need to access so let's say const addon = "Book". However, I don't know the key name beforehand. So the following code works but I need to somehow not hard code the key parameter but rather use the string value incoming from the const addon. I am not quite sure how to do this please point me to the right documentation or explain how to achieve the wanted result.

const columns = levelOne.Book && Object.keys(levelOne.Book);

However, as the incoming param might not be "Book" but anything else it will only work for this case. It is guaranteed that there is a key-value pair where the key bears the name stored in the string value of addon.


Solution

  • You can use a variable as the key. For example, levelOne[variable] where variable is the string that you want to use as the key. Also, you can get the keys through Object.keys(levelOne) and then you can set variable value from the keys array.