MMJ
MMJ

Reputation: 309

How to call object in array from it's name

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

Answers (1)

CertainPerformance
CertainPerformance

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 trimming 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

Related Questions