Reputation: 309
I have this array categories = [Sports, Kids]
Where Sports
and Kids
are not strings, they're objects imported after export const Sports = {...}
export from another file.
I Have also categoriesLoop = ['Sports', 'Kids']
to loop over the categories in <select>
to do this: categoriesLoop.map(category => <option>{category}</option>
in react.
Now the question how to access the Sports
and Kids
objects from their string names within their array - categories
- ?
Like, When I do this in my select onChange
:
const category = e.currentTarget.value;
console.log(categories[category]);
I get undefined, Because the string 'Sports' not exists in the categories
which has an objects not strings.
How to get that Sports
object in categories
When I have the string 'Sports'
?
Am I missing something?
Upvotes: 0
Views: 56
Reputation: 370989
Use an object instead of an array, and then just use bracket notation:
const categories = { Sports, Kids };
// ...
const category = e.currentTarget.value;
console.log(categories[category]);
Capitalization matters - here, you'd have to input Sports
exactly, or Kids
exactly. Since this sounds like it's from user input, you might consider using lower-cased keys, and then trim
ming and lower-casing the input value:
const categories = { sports: Sports, kids: Kids };
// ...
const category = e.currentTarget.value.trim().toLowerCase();
console.log(categories[category]);
Upvotes: 3